我试图使用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();
}
}我的测试文件目前看起来如下:
tests/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不是一个函数
我尝试过一些没有起作用的东西,这感觉是最接近的,但我无法理解为什么jest.mock不能正常工作。我看了几个例子,但仍然找不出为什么我不能让嘲弄的工作。有人能帮我指出我做错了什么吗?
发布于 2019-10-04 03:20:30
由于您拥有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");https://stackoverflow.com/questions/58222348
复制相似问题