Jest testing tips

Jest mocks should always be at the root of the test file

Not inside a test function.

https://jestjs.io/docs/manual-mocks

Configuring Jest

  1. https://jestjs.io/docs/configuration

jest-dom

https://testing-library.com/docs/ecosystem-jest-dom/

How to check multiple arguments on multiple calls for jest spies?

https://stackoverflow.com/questions/40018216/how-to-check-multiple-arguments-on-multiple-calls-for-jest-spies

Use toHaveBeenNthCalledWith

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenNthCalledWith(1, 'lemon');
  expect(drink).toHaveBeenNthCalledWith(2, 'octopus');
});

This can also work.

expect(mockFn.mock.calls[0][0]).toEqual('first argument');
expect(mockFn.mock.calls[0][1]).toEqual('second argument');

How to test chaining calls?

If you need to chain more than one call after another you can do something like this:

const callAService(value) => {
    const firstResponse = serviceOne(value)
    return serviceTwo(firstResponse)
}

it('should behave some way when provided a value', ()=> {
      serviceOne.mockImplementation((value)=> if(value === 1) return 2 )
      serviceTwo.mockImplementation((value)=> if(value === 2) return 3)

      const actual = callAService(1)
      expect(actual).toEqual(3)
})

Cheat sheet

  1. https://www.codecademy.com/learn/learn-react-testing/modules/jest/cheatsheet
  2. https://github.com/sapegin/jest-cheat-sheet
  3. https://devhints.io/jest

Links to this note