Mock a function from another file - Jest

Solution 1:

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.

Solution 2:

I got the same question and finally I find the solution. I post it here for the one who got the same issue.

Jest test file:

import * as utils from "./demo/utils";
import { welcomeMessage } from "./demo/login";

// option 1: mocked value
const mockGetData = jest.spyOn(utils, "getData").mockReturnValue("hello");

// option 2: mocked function
const mockGetData = jest.spyOn(utils, "getData").mockImplementation((name) => "Hello !!! " + name);

describe("User actions", () => {
    it("should get username", () => {
        const value = "Hello !!! Jest";
        expect(welcomeMessage("Jest")).toEqual(value);
    });
});

references: https://jestjs.io/docs/jest-object#jestfnimplementation

jest.spyOn(object, methodName)

Creates a mock function similar to jest.fn but also tracks calls to object[methodName]. Returns a Jest mock function.

Note: By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries. If you want to override the original function, you can use:

jest.spyOn(object, methodName).mockImplementation(() => customImplementation)

or

object[methodName] = jest.fn(() => customImplementation);