简体   繁体   中英

Jest mocking a module

I'm trying to mock a module import using Jest and I'm struggling for some reason. I've got the following code:

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

My test file currently looks like:

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);
    });
});

At the moment however I'm getting an error in my test:

TypeError: getRolesFunc.mockImplementation is not a 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. I've looked at a few examples and still can't work out why this I can't get mocking working. Can anyone help point out what I've done wrong?

As you have 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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