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

259
Visualizações
Manual mock of object in Jest

I'm trying to figure out manual mocks in Jest. I think this should be easy...but it isn't.

My project directories are like

  • __tests__
    • user-test.js
  • models
    • user.js
    • __mocks__
      • user.js
  • node_modules
    • ...
  • package.json

Both models/user.js and models/__mocks__/user.js have the same code:

module.exports = {
    create(username, password) {
        return new Promise(function(resolve, reject) {
            setTimeout(function() {
                resolve({"username":username, "password": password});
            }, 100);
        });
    }
}

The file __tests__/user-test.js looks like this:

test('user creation works', () => {
    const user = require('../models/user');
    //const user = jest.mock('../models/user');
    return user.create("mitchell", "boo");
});

This works fine, tests pass, but when I change it to:

test('user creation works', () => {
    //const user = require('../models/user');
    const user = jest.mock('../models/user');
    return user.create("mitchell", "boo");
});

It doesn't work, and spits out:

 FAIL  __tests__\user-test.js
  ● user creation works

    TypeError: user.create is not a function

      at Object.<anonymous>.test (__tests__\user-test.js:4:17)
      at process._tickCallback (internal\process\next_tick.js:103:7)
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Ah! Figured it out! My folder structure is fine. Turns out I had a misunderstanding as to what "jest.mock" actually did. "jest.mock" changes the behavior of the node "require" function to use the mock, it doesn't do a require itself.

My test should have looked like:

jest.mock('../models/user');
test('user creation works', () => {
    const user = require('../models/user');
    return user.create("mitchell", "boo");
});
over 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