Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda