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

319
Views
¿Cómo cambiar el comportamiento de una importación simulada?

Estoy bastante confundido con la burla en Jest y cómo probar las implementaciones por unidad. La cosa es que quiero burlarme de diferentes comportamientos esperados.

¿Hay alguna manera de lograr esto? ya que las importaciones solo pueden estar en la parte superior del archivo y para poder burlarse de algo, debe declararse antes de la importación. También intenté pasar una función local para poder sobrescribir el comportamiento, pero jest se queja de que no puedes pasar nada local.

 jest.mock('the-package-to-mock', () => ({ methodToMock: jest.fn(() => console.log('Hello')) })); import * as theThingToTest from '../../../app/actions/toTest' import * as types from '../../../app/actions/types' it('test1', () => { expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE) }) it('test2', () => { //the-package-to-mock.methodToMock should behave like something else expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE) })

internamente, como puede imaginar, theThingToTest.someAction() usa the-package-to-mock.methodToMock

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede simular con un espía e importar el módulo simulado. En su prueba, establece cómo debe comportarse el simulacro usando mockImplementation :

 jest.mock('the-package-to-mock', () => ({ methodToMock: jest.fn() })); import { methodToMock } from 'the-package-to-mock' it('test1', () => { methodToMock.mockImplementation(() => 'someValue') }) it('test2', () => { methodToMock.mockImplementation(() => 'anotherValue') })
over 4 years ago · Santiago Trujillo Report

0

Yo uso el siguiente patrón:

 'use strict' const packageToMock = require('../path') jest.mock('../path') jest.mock('../../../../../../lib/dmp.db') beforeEach(() => { packageToMock.methodToMock.mockReset() }) describe('test suite', () => { test('test1', () => { packageToMock.methodToMock.mockResolvedValue('some value') expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE) }) test('test2', () => { packageToMock.methodToMock.mockResolvedValue('another value') expect(theThingToTest.someAction().type).toBe(types.OTHER_TYPE) }) })

Explicación:

Se burla de la clase que está tratando de usar en el nivel del conjunto de pruebas, asegúrese de que el simulacro se restablezca antes de cada prueba y para cada prueba use mockResolveValue para describir lo que se devolverá cuando se devuelva el simulacro.

over 4 years ago · Santiago Trujillo Report

0

Otra forma es usar jest.doMock(moduleName, factory, options) .

P.ej

the-package-to-mock.ts :

 export function methodToMock() { return 'real type'; }

toTest.ts :

 import { methodToMock } from './the-package-to-mock'; export function someAction() { return { type: methodToMock(), }; }

toTest.spec.ts :

 describe('45006254', () => { beforeEach(() => { jest.resetModules(); }); it('test1', () => { jest.doMock('./the-package-to-mock', () => ({ methodToMock: jest.fn(() => 'type A'), })); const theThingToTest = require('./toTest'); expect(theThingToTest.someAction().type).toBe('type A'); }); it('test2', () => { jest.doMock('./the-package-to-mock', () => ({ methodToMock: jest.fn(() => 'type B'), })); const theThingToTest = require('./toTest'); expect(theThingToTest.someAction().type).toBe('type B'); }); });

resultado de la prueba unitaria:

 PASS examples/45006254/toTest.spec.ts 45006254 ✓ test1 (2016 ms) ✓ test2 (1 ms) -----------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s -----------|---------|----------|---------|---------|------------------- All files | 100 | 100 | 100 | 100 | toTest.ts | 100 | 100 | 100 | 100 | -----------|---------|----------|---------|---------|------------------- Test Suites: 1 passed, 1 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 3.443 s

código fuente: https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/45006254

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