Jest: Clearing Module Mocks Effortlessly

Michael T. Andemeskel
2 min readApr 27, 2021

--

Photo by Oskar Yildiz on Unsplash

I have a query module that is used throughout my app. Therefore, this module gets mocked often in my tests. To save time, I mocked it globally through a setup file that is loaded every time Jest runs. It works almost flawlessly, my specs are cleaner, and I can test exactly what I want.

I realized, however, that the tests for the query module were passing regardless of what I did to the module. I had inadvertently broken the module’s tests by globally mocking it.

I tried removing the mock using: jest.restoreAllMocks , jest.clearAllMocks, and jest.resetAllMocks in all forms and combinations but nothing worked. Then I found jest.unmock. This function lets you pass the module name or path and it will ensure the module is never mocked. It is simple and it will let you mock the file in other test suits. It’s perfect. Here is how you can use it.

The Mock

Here I mock the query module, specifically the active_bank_request object, using jest.mock. The mock listens to the query method on active_bank_request and returns a mock response.

jest.mock('@/queries/accounts_query', () => {  return {    active_bank_request: {      query: () => new Promise(resolve => resolve(mock_accounts))    }  }})

Notice the path of the module I used in the jest.mock call. That needs to be the same path you pass to jest.unmock.

The @ is a shortcut for the src folder so I don’t have to write ../../ for every path.

Clearing the Mock

In the spec for accounts_query I unmock the module calling jest.unmock and passing it the path to the module.

describe('Accounts Query', () => {  beforeAll(() => {    jest.unmock('@/queries/accounts_query')  })
describe('Active Accounts', () => { // tests })})

That’s it, happy testing!

Sources

More content at plainenglish.io

--

--

Michael T. Andemeskel
Michael T. Andemeskel

Written by Michael T. Andemeskel

I write code and occasionally, bad poetry. Thankfully, my code isn’t as bad as my poetry.

No responses yet