简体   繁体   中英

Mocking static class function in jest doesn't work

Given a very basic javscript class

Foo.js

export default class Foo {
    static bar() {
        console.log("bar");
    }
}

how can I mock the bar function?

Here is what i thought should work (but isn't):

Foo.test.js

import Foo from "./Foo.js";

it("test", () => {
    jest.mock("./Foo.js"); // mock Foo class
    const myMock = jest.fn(); // create a new mocking function
    Foo.prototype.bar = myMock;

    Foo.bar();

    console.log(myMock.mock.calls);
});

But then Foo.bar() call in the test calls the original function (so "bar" get logged) and console.log(myMock.mock.calls); prints a empty list, so the mocking function istn used.

What am I doing wrong?

The class was mocked after it was imported, the mock doesn't affect it. jest.mock should be either moved to top level so it could be hoisted before import , or in case the class doesn't need to be mocked for the whole suite, import should be placed inside a test and possibly replaced with require .

bar method isn't mocked because it's static method but it's prototype method that was mocked. Methods shouldn't be mocked by assignment because this prevents them from being restored.

It should be:

jest.spyOn(Foo, 'bar').mockImplementation(() => ...);

It should preferably be restored with jest.restoreAllMocks() or restoreMocks configuration option to not affect other tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM