开玩笑嘲笑一个模块

时间:2019-10-03 15:26:14

标签: 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();
    }
}

我的测试文件当前看起来像:

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为何无法正常工作。我看了几个例子,但仍然无法弄清楚为什么我无法进行模拟。谁能帮我指出我做错了什么?

1 个答案:

答案 0 :(得分:1)

有了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");