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 settingsclearMocks,resetMocks,restoreMocks, andresetModulesare set tofalseby 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 isclearMocks:

Automatically clear mock calls, instances, contexts and results before every test. Equivalent to callingjest.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 likemockReturnValueOnceinstead of onlymockReturnValue. But ifclearMocksis false by default, then that context can be carried between tests.

Take this example function:

1exportfunctionrandomNumber() {2returnMath.random();3}

And this simple test for it:

1jest.mock('.');23const{randomNumber}=require('.');45describe('tests',()=>{6randomNumber.mockReturnValue(42);78it('should return 42',()=>{9constrandom=randomNumber();1011expect(random).toBe(42);12expect(randomNumber).toBeCalledTimes(1)13});14});

The test passes and works as expected. However, if we add another test to our test suite:

1jest.mock('.');23const{randomNumber}=require('.');45describe('tests',()=>{6randomNumber.mockReturnValue(42);78it('should return 42',()=>{9constrandom=randomNumber();1011expect(random).toBe(42);12expect(randomNumber).toBeCalledTimes(1)13});1415it('should return same number',()=>{16constrandom1=randomNumber();17constrandom2=randomNumber();1819expect(random1).toBe(42);20expect(random2).toBe(42);2122expect(randomNumber).toBeCalledTimes(2)23});24});

Our second test fails with the error:

1Error: expect(jest.fn()).toBeCalledTimes(expected)23Expected number of calls:24Received number of calls:3

And even worse, if we change the order of our tests:

1jest.mock('.');23const{randomNumber}=require('.');45describe('tests',()=>{6randomNumber.mockReturnValue(42);78it('should return same number',()=>{9constrandom1=randomNumber();10constrandom2=randomNumber();1112expect(random1).toBe(42);13expect(random2).toBe(42);1415expect(randomNumber).toBeCalledTimes(2)16});1718it('should return 42',()=>{19constrandom=randomNumber();2021expect(random).toBe(42);22expect(randomNumber).toBeCalledTimes(1)23});24});

We get the same error as before, but this time forshould return 42instead ofshould return same number.

EnablingclearMocksin your Jest configuration ensures that every mock’s context is reset between tests. You can achieve the same result by addingjest.clearAllMocks()to yourbeforeEach()functions. But this isn’t a great idea as it means you have to remember to add it to each test file to make your tests safe, instead of usingclearMocksto make them all safe by default.

resetMocks

Next up isresetMocks:

Automatically reset mock state before every test. Equivalent to callingjest.resetAllMocks()before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.

resetMockstakesclearMocksa step further, by clearing the implementation of any mocks. However, you need to use it in addition toclearMocks.

Going back to my first example again, I’m going to move the mock setup inside the first test caserandomNumber.mockReturnValue(42);.

1describe('tests',()=>{2it('should return 42',()=>{3randomNumber.mockReturnValue(42);4constrandom=randomNumber();56expect(random).toBe(42);7expect(randomNumber).toBeCalledTimes(1)8});910it('should return 42 twice',()=>{11constrandom1=randomNumber();12constrandom2=randomNumber();1314expect(random1).toBe(42);15expect(random2).toBe(42);1617expect(randomNumber).toBeCalledTimes(2)18});19});

Logically, you might expect this to fail, but it passes! Jest mocks are global to the file they’re in. It doesn’t matter whatdescribe,it, ortestscope you use. And if I change the order of tests again, they fail. This makes it very easy to write tests that leak state and are order-dependent.

EnablingresetMocksin your Jest context ensures that every mock implementation is reset between tests. Like before, you can also addjest.resetAllMocks()tobeforeEach()in every test file. But it’s a much better idea to make your tests safe by default instead of having to opt-in to safe tests.

restoreMocks

Next isrestoreMocks:

Automatically restore mock state and implementation before every test. Equivalent to callingjest.restoreAllMocks()before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation.

restoreMockstakes test isolation and safety to the next level.

Let me rewrite my example a little bit, so instead of mocking the function directly, I’m mockingMath.random()instead.

1const{randomNumber}=require('.');23constspy=jest.spyOn(Math,'random');45describe('tests',()=>{6it('should return 42',()=>{7spy.mockReturnValue(42);8constrandom=randomNumber();910expect(random).toBe(42);11expect(spy).toBeCalledTimes(1)12});1314it('should return 42 twice',()=>{15spy.mockReturnValue(42);1617constrandom1=randomNumber();18constrandom2=randomNumber();1920expect(random1).toBe(42);21expect(random2).toBe(42);2223expect(spy).toBeCalledTimes(2)24});25});

WithclearMocksandresetMocksenabled, andrestoreMocksdisabled, my tests pass. But if I enablerestoreMocksboth tests fail with an error message like:

1Error: expect(received).toBe(expected)// Object.is equality23Expected:424Received: 0.503533695686772

restoreMockshas restored the original implementation ofMath.random()before each test, so now I’m getting an actual random number instead of my mocked return value of42. This forces me to be explicit about not only the mocked return values I’m expecting, but the mocks themselves.

To fix my tests I can set up my Jest mocks in each individual test.

1describe('tests',()=>{2it('should return 42',()=>{3constspy=jest.spyOn(Math,'random').mockReturnValue(42);4constrandom=randomNumber();56expect(random).toBe(42);7expect(spy).toBeCalledTimes(1)8});910it('should return 42 twice',()=>{11constspy=jest.spyOn(Math,'random').mockReturnValue(42);1213constrandom1=randomNumber();14constrandom2=randomNumber();1516expect(random1).toBe(42);17expect(random2).toBe(42);1819expect(spy).toBeCalledTimes(2)20});21});

resetModules

Finally, we haveresetModules:

By default, each test file gets its own independent module registry. EnablingresetModulesgoes a step further and resets the module registry before running each individual test. This is useful to isolate modules for every test so that the local module state doesn’t conflict between tests. This can be done programmatically usingjest.resetModules().

Again, this builds on top ofclearMocks,resetMocks, andrestoreMocks. I don’t think this level of isolation is required for most tests, but I’m a completionist.

Let’s take my example from above and expand it to include some initialization that needs to happen before I can callrandomNumber. Maybe I need to make sure there’s enough entropy to generate random numbers? My module might look something like this:

1letisInitialized=false;23exportfunctioninitialize() {4isInitialized=true;5}67exportfunctionrandomNumber() {8if(!isInitialized){9thrownewError();10}1112returnMath.random();13}

I also want to write some tests to make sure that this works as expected:

1constrandom=require('.');23describe('tests',()=>{4it('does not throw when initialized',()=>{5expect(()=>random.initialize()).not.toThrow();6});78it('throws when not initialized',()=>{9expect(()=>random.randomNumber()).toThrow();10});11});

initializeshouldn’t throw an error, butrandomNumbershould throw an error ifinitializeisn’t called first. Great! Except it doesn’t work. Instead I get:

1Error: expect(received).toThrow()23Receivedfunctiondid not throw

That’s because without enablingresetModules, the module is shared between all tests in the file. So when I calledrandom.initialize()in my first test,isInitializedis still true for my second test. But once again, if I were to switch the order of my tests in the file, they would both pass. So my tests are order-dependent again!

EnablingresetModuleswill give each test in the file a fresh version of the module for each test. Though, this might actually be a case where you want to usejest.resetAllModules()in yourbeforeEach()instead of enabling it globally. This kind of isolation isn’t required for every test. And if you’re usingimportinstead ofrequire, the syntax can get very awkward very quickly if you’re trying to avoid an'import' and 'export' may only appear at the top levelerror.

TL;DR reset all of the things

By default, Jest tests are only isolated at the file level. If you really want to make sure your tests are safe and isolated, add this to your Jest config:

1{2clearMocks:true,3resetMocks:true,4restoreMocks:true,5resetModules:true// It depends6}

There isa suggestionto make this part of the default configuration. But until then, you’ll have to do it yourself.