Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda