jest.mock() doesn't work inside tests, only outside tests

Viewed 4576

I have a simple suite of tests where in some cases I want to mock a module and in some cases not. However, jest.mock() works only if it's placed outside tests. Anyone has an idea why is that and what I'm doing wrong?

This is the actual import of a function I want to mock

import {hasSupport, getCallingCode} from 'utils/countryCallingCode';

And this is the mock of this function:

jest.mock('utils/countryCallingCode', () => ({
    getCallingCode: () => '1',
    hasSupport: () => true,
  }));

Now, the working scenario is:

//imports
//mock

describe('...', () -> {
    it('...', () -> {

    });
});

This DOESN'T work:

//imports

describe('...', () -> {
    //mock

    it('...', () -> {

    });
});

This also DOESN'T work:

//imports

describe('...', () -> {
    it('...', () -> {
        //mock
    });
});
1 Answers

Jest automatically hoists jest.mock calls in ES modules to the top of the file, before any import statements. This is done in order to allow the use of the mocked module by other modules in the tree.

The Jest documentation also provides an example repository to explain how Jest mocking works.

If you want to prevent this automatic behaviour, you can use jest.dontMock.

Related