javascript - 开 Jest mock 一个模块

标签 javascript unit-testing jestjs

我正在尝试使用 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/

相关文章:

javascript - 位置 4 的 JSON 中的意外标记 <

angular - 在 Jasmine + Angular 中模拟 'window' 对象

java - 检查@RequestMapping - 单元测试

java - 在 Google App Engine 的 VFS 中编译 JSP 文件

node.js - 使用 Jest(和 mockgoose)测试 Node.js API

javascript - 如何测试更改组件状态的函数?

javascript - 我怎样才能在ubuntu中运行 "node index.js"

javascript - 切换类时如何使div缓慢移动?

javascript - 如何获取具有绝对位置的元素的绝对坐标(JavaScript,浏览器)

javascript - 不支持从 "describe"返回 Promise。测试必须同步定义