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

147
Visualizações
Unable to mock a method of an object with jest

I can't seem to mock a method of an object using jest.

The following code below will show a successful test when you run the command jest -- Feature.test.js

// ------ Feature.js
import Helper from './Helper';
const Feature = (arg1) => {
    const helper = new Helper();
    return helper.isValid(arg1 === 1, 'other');
    ;
};
export default Feature;



-------------------------------------------

// ------ Feature.test.js
//import Helper from './Helper';
import Feature from './Feature';

//jest.mock('./Helper');
describe('Feature', () => {
it('test', ()=>{
    //const helper = new Helper();
    //helper.isValid.mockReturnValue(true);
    const result = Feature('fake value');
    console.log(result);
    expect(result.toString()).toBe('false');
});
});

But the moment I uncomment the lines in Feature.test.js like so:

// ------ Feature.test.js
import Helper from './Helper';
import Feature from './Feature';

jest.mock('./Helper');
describe('Feature', () => {
it('test', ()=>{
    const helper = new Helper();
    helper.isValid.mockReturnValue(true);
    const result = Feature('fake value');
    console.log(result);
    expect(result.toString()).toBe('false');
});
});

and jest -- Feature.test.js again, I get this output:

> jest "Feature.test.js"

  console.log
    undefined

      at Object.<anonymous> (./Feature.test.js:11:13)

 FAIL  ./Feature.test.js
  Feature
    ✕ test (21 ms)

  ● Feature › test

    TypeError: Cannot read property 'toString' of undefined

      10 |     const result = Feature('fake value');
      11 |     console.log(result);
    > 12 |     expect(result.toString()).toBe('false');
         |                   ^
      13 | });
      14 | });
      15 |

      at Object.<anonymous> (./Feature.test.js:12:19)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.564 s, estimated 1 s
Ran all test suites matching /Feature.test.js/i.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! john@1.0.0 test: `jest "Feature.test.js"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the anzen@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


What am I doing wrong? Why won't my mock return a value? What's the correct way to mock a method of an object being used in a module?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This shows example of how to mock a method of an object:

import Helper from './Helper';
import Feature from './Feature';

describe('Feature', () => {

    beforeEach(() => {
        jest.spyOn(Helper.prototype, 'isValid').mockImplementation(() => true);
    });

    it('test1', () => {
        const result = Feature('fake value');
        console.log(result);
        expect(result.toString()).toBe('true');
    });

    it('test2', () => {
        const result = Feature(1);
        console.log(result);
        expect(result.toString()).toBe('true');
    });

});
about 4 years ago · Juan Pablo Isaza 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