How to improve your tests using Jest

Jest
Web Dev

Fri Dec 30 2022

Use Jest.SpyOn Correctly

When using Jest.SpyOn you do not need to set it as a const, you can reference any spied on functions by doing the following

Don't

import example from 'example';

const spyedOnExampleMethod = jest.spyOn(example, 'method');

// Shortened for brevity 

it('example test', () => {
expect(spyedOnExampleMethod).toBeCalledTimes(1);
});

Do

import example from 'example';

 jest.spyOn(example, 'method');

// Shortened for brevity 

it('example test', () => {
expect(example.method).toBeCalledTimes(1);
});

 

Clear Mocks Every Test

It is good practice to ensure that your tests clear all the mocks and spys for each test. This is good practice because you can run in to instances where previous tests mocks can run into the next tests which could potentially lead to incorrect tests passing.

// Shortened for Brevity

afterEach(() => {
jest.clearAllMocks();
});