DEV Community

Cover image for My "Whoa, I didn't know that!" moments with Jest

My "Whoa, I didn't know that!" moments with Jest

briwa on May 26, 2019

Jest has always been my go-to unit testing tool. It is so robust I'm starting to think that I've always been underutilizing it. Although the tests ...
Collapse
 
wes profile image
Wes Souza

Here's an extra one I love to use:

const anyObject = {
  complex: true,
  otherProperties: "yes",
  foo: "bar",
};

expect(anyObject).toEqual(expect.objectContaining({ foo: "bar" }))
Enter fullscreen mode Exit fullscreen mode

expect.objectContaining docs.

Really useful for testing objects where you only care about a small part that changes, instead of using snapshots.

Collapse
 
aleccool213 profile image
Alec Brunelle

+1 for not leaking mocks into global state :)

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

👏 Bravo for sharing the ability to iterate over test cases. I’ve been looking for something like that for a long time. I’ve hand rolled it myself in jest, Xunit, Nunit, mocha, jasmine, etc. I can’t wait to try this out on Tuesday when I go back to work. Thank you! :)

Collapse
 
gualison profile image
Alberto Gualis

Great post! Thank you!

I'll also add one little tip for "#3. Snapshot testing on a non-UI elements":

you can replace toMatchSnapshot() by .toMathInlineSnapshot() (check jestjs.io/docs/en/snapshot-testing...) so jest will automatically write all the expected values in your tests file so it's easier to review them (it will even pretty-format them if you use prettier!)

Happy testing!

Collapse
 
javaguirre profile image
Javier Aguirre • Edited

Majestic looks cool! I like to launch Jest from vs code using ‘—watch’, so it’s running while changing key parts of my components.

Another cool way of using jest is when using the storybook plugin for Structural Testing in React.

Collapse
 
iomtt94 profile image
Bohdan Artemenko • Edited

I don't know is it correct, my first example:

test('Created with old code style where object has 2 fields', () => {
    expect(github).toMatchObject({
      'name': expect.any(String),
      'ip': expect.any(String),
    });
  });
Collapse
 
slidenerd profile image
slidenerd

i dont use any matcher except toEqual because everytime jest upgrades they always mess a few matchers here and there, if i dont use their fancy matchers, my tests have the lowest chance of breaking on every major upgrade

Collapse
 
tcelestino profile image
Tiago Celestino

Great tips!!

Collapse
 
srshifu profile image
Ildar Sharafeev

Did you know about findRelatedTests option? I wrote an article about it: dev.to/srshifu/under-the-hood-how-...