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

186
Views
Problemas para burlarse del módulo ES6 usando jest.unstable_mockModule

Estoy intentando simular una llamada a una función de instancia de clase en un módulo ES6 importado por el código bajo prueba. Seguí el progreso de la compatibilidad con ES6 y finalmente encontré este PR https://github.com/facebook/jest/pull/10976 que mencionaba que en 27.1.1 se agregó compatibilidad con jest.unstable_mockModule. Actualicé mi versión de Jest para aprovechar y, aunque la prueba no da error, tampoco parece burlarse del módulo.

Este es el módulo bajo prueba:

 // src/Main.mjs import Responder from './Responder.mjs' import Notifier from './Notifier.mjs' export default { async fetch(request, environment, context) { let response try { response = new Responder(request, environment, context).respond() } catch (error) { return new Notifier().notify(error) } return response } }

Aquí está la prueba:

 // test/Main.test.mjs import { jest } from '@jest/globals' import main from '../src/Main.mjs' describe('fetch', () => { test('Notifies on error', async () => { const mockNotify = jest.fn(); jest.unstable_mockModule('../src/Notifier.mjs', () => ({ notify: mockNotify })) const notifierMock = await import('../src/Notifier.mjs'); await main.fetch(null, null, null) expect(mockNotify).toHaveBeenCalled() }) })

Estoy tratando de simular la llamada a Notify para esperar que se haya llamado y, mientras se ejecuta, genera una excepción desde dentro de Notifier.notify() que se supone que se burlará, por lo que parece que no es ser burlado en absoluto.

¿Qué me estoy perdiendo? Cualquier ayuda es muy apreciada. 🙏

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Creo que es porque estás importando main al comienzo del archivo. Debe hacer una importación dinámica de la misma manera que Notifier.mjs

 // test/Main.test.mjs import { jest } from '@jest/globals' describe('fetch', () => { test('Notifies on error', async () => { const mockNotify = jest.fn(); jest.unstable_mockModule('../src/Notifier.mjs', () => ({ notify: mockNotify })) const notifierMock = await import('../src/Notifier.mjs'); const main = await import('../src/Main.mjs'); await main.fetch(null, null, null) expect(mockNotify).toHaveBeenCalled() }) })
about 4 years ago · Juan Pablo Isaza Report

0

No entiendo exactamente la confusión final. Pero para los fundamentos, para burlarse de un atributo/método particular de una clase importada, debe burlarse de la clase en sí y luego burlarse de las funciones internas.

Por lo tanto, según su código, puede intentar algo como:

 import { jest } from '@jest/globals' import main from '../src/Main.mjs' import Notifier from './Notifier.mjs' jest.mock('./Notifier.mjs', () => ({ notify: jest.fn() })) describe('fetch', () => { test('Notifies on error', async () => { await main.fetch(null, null, null) expect(mockNotify).toHaveBeenCalled() }) })
about 4 years ago · Juan Pablo Isaza 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!