Jest testing tips
Table of Contents
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
jest-dom
https://testing-library.com/docs/ecosystem-jest-dom/
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)
})