Is your Jest test suite failing you? You might not be using the testing framework's full potential, especially when it comes to preventing state leakage between tests. The Jest settings clearMocks, resetMocks, restoreMocks, and resetModules are set to false by default. If you haven't changed these defaults, your tests might be fragile, order-dependent, or just downright wrong. In this blog post, I'll dig into what each setting does, and how you can fix your tests.
Your Jest tests might be wrong Is your Jest test suite failing you? You might not be using the testing framework's full potential, especially when it comes to preventing state leakage between tests. The Jest settings clearMocks , resetMocks , restoreMocks , and resetModules are set to false by default. If you haven't changed these defaults, your tests might be fragile, order-dependent, or just downright wrong. In this blog post, I'll dig into what each setting does, and how you can fix your tests. clearMocks First up is clearMocks : Automatically clear mock calls, instances, contexts and results before every test. Equivalent to calling jest.clearAllMocks() before each test. This does not remove any mock implementation that may have been provided. Every Jest mock has some context associated with it. It's how you're able to call functions like mockReturnValueOnce instead of only mockReturnValue . But if clearMocks is false by default, then that context can be carried between tests. Take this example function: 1 export function randomNumber() { 2 return Math .random(); 3 } And this simple test for it: 1 jest.mock( '.' ); 2 3 const { randomNumber } = require ( '.' ); 4 5 describe( 'tests' , () => { 6 randomNumber.mockReturnValue( 42 ); 7 8 it( 'should return 42' , () => { 9 const random = randomNumber(); 10 11 expect(random).toBe( 42 ); 12 expect(randomNumber).toBeCalledTimes( 1 ) 13 }); 14 }); The test passes and works as expected. However, if we add another test to our test suite: 1 jest.mock( '.' ); 2 3 const { randomNumber } = require ( '.' ); 4 5 describe( 'tests' , () => { 6 randomNumber.mockReturnValue( 42 ); 7 8 it( 'should return 42' , () => { 9 const random = randomNumber(); 10 11 expect(random).toBe( 42 ); 12 expect(randomNumber).toBeCalledTimes( 1 ) 13 }); 14 15 it( 'should return same number' , () => { 16 const random1 = randomNumber(); 17 const random2 = randomNumber(); 18 19 expect(random1).toBe( 42 ); 20 expect(random2).toBe( 42 ); 21 22…