I give up. I can't figure out how to get my module to use my mock of the CommonJS named export uuidv4. I've tried using jest.mock(), jest.spyOn(), and just setting the function equal to a jest.fn() as shown below (which is what I typically and successfully use in my other tests), but none of these approaches are working for me.
Here is the essence of the last testing attempt mentioned above:
// myModule.test.js
const { v4: uuidv4 } = require('uuid');
const myModule = require('./myModule');
describe(`Tests for myModule'`, () => {
test(`First test`, async () => {
uuidv4 = jest.fn().mockReturnValueOnce("custom-uuid");
await myModule.someFunction();
expect(uuidv4).toHaveBeenCalled();
});
});
// myModule.js
const { v4: uuidv4 } = require('uuid');
async function someFunction() {
const id = uuidv4();
// ...do stuff with 'id'
}
module.exports = {someFunction};
No matter which approach I've tried (of the 3 mentioned above), I just can't get myModule.someFunction to make use of the mock I've created in my test for uuidv4.
Anyone know how to do this without using manual mocks?
Thank you for the help!!!
I was able to make this work using the answer found here.
https://ilikekillnerds.com/2020/04/how-to-mock-uuid-in-jest/
One thing I'm making a note for myself about this is that this worked...
jest.mock("../../../../../../functions/api/node_modules/uuid", () => ({ v4: () => "2306beb3-8833-40a5-b3f4-a8daab755251" }));
...but this did not...
const rootDir = "../../../../../..";
const uuidModule = `${rootDir}/functions/api/node_modules/uuid`;
jest.doMock(uuidModule, () => ({ v4: () => "2306beb3-8833-40a5-b3f4-a8daab755251" }));