简体   繁体   English

Jest mocking 一个模块

[英]Jest mocking a module

I'm trying to mock a module import using Jest and I'm struggling for some reason.我正在尝试使用 Jest 模拟模块导入,但由于某种原因我正在苦苦挣扎。 I've got the following code:我有以下代码:

src/elastic.js src/elastic.js

const getRolesFunc = elasticClient => async username => {
   // Do some stuff
}

module.exports = { getRolesFunc };

src/handlerFactory.js src/handlerFactory.js

const { getRolesFunc } = require("../src/elastic");

const handlerFactory = elasticClient => 
    async (event) =>  {
        const getRolesAsync = getRolesFunc(elasticClient);
        const roles = await getRolesAsync();
    }
}

My test file currently looks like:我的测试文件目前看起来像:

tests/handlerFactory.unit.test.js测试/handlerFactory.unit.test.js

const { handlerFactory } = require("../src/handlerFactory");
const { getRolesFunc } = require("../src/elastic");

jest.mock("../src/elastic", () => ({
    getRolesFunc: jest.fn(),
}));

describe("handlerFactory", () => {

    it("handler returns correct response", async () => {
        getRolesFunc.mockImplementation(() => "foo");

        // Call the handler to get our actual result
        const handlerAsync = handlerFactory({});
        const result = await handlerAsync(event);
    });
});

At the moment however I'm getting an error in my test:然而,目前我在测试中遇到错误:

TypeError: getRolesFunc.mockImplementation is not a function类型错误:getRolesFunc.mockImplementation 不是 function

I've tried a few things none of which worked, this feels like the closest but I can't work out why the jest.mock isn't working correctly.我已经尝试了一些没有奏效的方法,这感觉是最接近的,但我无法弄清楚为什么jest.mock不能正常工作。 I've looked at a few examples and still can't work out why this I can't get mocking working.我查看了一些示例,但仍然无法弄清楚为什么我无法让 mocking 工作。 Can anyone help point out what I've done wrong?谁能帮忙指出我做错了什么?

As you have module.exports = { getRolesFunc };正如你有module.exports = { getRolesFunc }; you need to below change in your code:您需要在代码中进行以下更改:

const { handlerFactory } = require("../src/handlerFactory");
const elasticObj = require("../src/elastic");

jest.mock("..src/elastic");
// in your example, now put below code:

elasticObj.getRolesFunc.mockImplementation(() => "foo");

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

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