Mock a function from another file – Jest

The first argument of jest.mock(...) must be a module path:

jest.mock('../../src/utils');

because the utils module is your code, not a 3rd lib, so you must learn manual mock of jest:
https://facebook.github.io/jest/docs/en/manual-mocks.html

if you had this file: src/utils.js

you can mock it by creating a file: src/__mocks__/utils.js

content of this file is the replication of the original but replace the implementation by getData = jest.fn()

on you test file, just call: jest.mock('../../src/utils'); at begin of file.

then when you’re familiar with, you can call that function inside beforeEach() and call its counter jest.unmock('../../src/utils'); insider afterEach()

An easy way to think about it is that:

when you call jest.mock('../../src/utils');, it means you tell jest that:

hey if the running test meets the line require('../../src/utils'), don’t load it, let load ../../src/__mocks__/utils.

Leave a Comment

tech