我正在尝试使用 Jest 模拟模块导入,但由于某种原因我很挣扎。我有以下代码:
src/elastic.js
const getRolesFunc = elasticClient => async username => {
// Do some stuff
}
module.exports = { getRolesFunc };
src/handlerFactory.js
const { getRolesFunc } = require("../src/elastic");
const handlerFactory = elasticClient =>
async (event) => {
const getRolesAsync = getRolesFunc(elasticClient);
const roles = await getRolesAsync();
}
}
我的测试文件当前如下所示:
测试/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);
});
});
目前我在测试中遇到错误:
TypeError: getRolesFunc.mockImplementation is not a function
我尝试了一些方法,但都不起作用,这感觉是最接近的,但我无法弄清楚为什么 jest.mock
无法正常工作。我看了几个例子,仍然无法弄清楚为什么我不能让 mock 工作。谁能帮我指出我做错了什么?
最佳答案
由于您有 module.exports = { getRolesFunc };
您需要在代码中进行以下更改:
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");
关于javascript - 开 Jest mock 一个模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58222348/