简体   繁体   English

Mocking static class function 最不工作

[英]Mocking static class function in jest doesn't work

Given a very basic javscript class给定一个非常基本的 javscript class

Foo.js

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

how can I mock the bar function?如何模拟酒吧 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);但随后在测试中调用Foo.bar()调用原始 function (因此“bar”被记录)和console.log(myMock.mock.calls); prints a empty list, so the mocking function istn used.打印一个空列表,因此使用了 mocking function 。

What am I doing wrong?我究竟做错了什么?

The class was mocked after it was imported, the mock doesn't affect it. class 导入后被模拟,模拟不影响它。 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 . jest.mock应该移动到顶层,以便在import之前将其提升,或者如果 class 不需要为整个套件进行模拟, import应该放在测试中并可能替换为require

bar method isn't mocked because it's static method but it's prototype method that was mocked. bar方法没有被模拟,因为它是 static 方法,但它是被模拟的原型方法。 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.最好使用jest.restoreAllMocks()restoreMocks配置选项恢复它,以免影响其他测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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