简体   繁体   English

在Jest中模拟导入

[英]Mocking an import in Jest

I have the following test: 我有以下测试:

const mockedObject = {
    mockedMethod: jest.fn((someKey, someValue) => {
        return {someKey: 'someValue'}
    })
};

jest.doMock('../myObject', () => {
    return mockedObject;
});


testedObject.testedMethod();
expect(mockedObject.mockedMethod).toHaveBeenCalled();

Here, in the testedObject , I am importing myObject . 在这里,在testedObject ,我正在导入myObject I would like to mock that import and pass mockedObject instead . 我想模拟该导入并mockedObject instead传递mockedObject instead

After looking at this question and this question , I think the above code should be good, however mockedObject.mockedMethod is never called even though testedObject is making the call. 细算这个问题,并且这个问题 ,我觉得上面的代码应该是不错的,但是mockedObject.mockedMethod不会被调用即使testedObject进行调用。

So what is wrong with the mocking done in this test? 那么,此测试中进行的模拟有什么问题呢?

You call 你打电话

testedObject.testedMethod() testedObject.testedMethod()

but expect 但期待

mockedObject.mockedMethod) mockedObject.mockedMethod)

try this code: 试试这个代码:

const mockedObject = {
    testedMethod: jest.fn((someKey, someValue) => {
        return {someKey: 'someValue'}
    })
};

jest.doMock('../myObject', () => {
    return mockedObject;
});


testedObject.testedMethod();
expect(mockedObject.testedMethod).toHaveBeenCalled();

I can think of some choices. 我可以想到一些选择。

One thing that could be happening is that you are mocking the import after your tested object has required it and you cannot modify that. 可能发生的一件事是,您在测试对象需要导入后对其进行模拟,而您无法对其进行修改。 If that is your case, then make sure you make the instance of the object only after you have modified the package. 如果是这种情况,请确保仅在修改程序包之后才创建对象的实例。

Another option is to create a folder mocks and create a file .js called exactly like your module or import and then return whatever you need. 另一种选择是创建一个文件夹嘲弄 ,并创建一个文件名为名为.js酷似你的模块或进口,然后返回你需要什么。 This works best for global dependencies. 这最适合全局依赖项。

Lastly, what you also can do is to make your tested object receive the dependency as a parameter, so you can override the import inside the file. 最后,您还可以做的是使您的测试对象将依赖项作为参数接收,因此您可以覆盖文件内部的导入。

Hope it helps 希望能帮助到你

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

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