Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
How do you mock the named export "uuidv4" using Jest and CommonJS?

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!!!

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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" }));
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!