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

662
Views
El método Jest spyOn sin la invocación de implementación simulada es una implementación simulada

Entonces, de acuerdo con la documentación de Jest y varias publicaciones en la web, y también lo creía, usar jest.spyOn(foo, "bar") envolvería la función especificada con métodos que nos permiten realizar afirmaciones sobre foo.bar sin cambiar la implementación real . Para cambiar la implementación, necesitaríamos usar mockImplementation , etc.

Sin embargo, tengo un problema en el que el uso jest.spyOn(foo, "bar") se comporta claramente como un simulacro de jest.fn() .

 /** * Test causing the issue */ test("when invoked with custom options does not override include locations setting", async () => { const defaultQueryConfig = { include: { locations: true } } const findFirstSpy = jest.spyOn(prismaConnection.event, "findFirst") await findOneEventByIdWithLocation(666, { include: { locations: false } }) expect(findFirstSpy).toHaveBeenCalledTimes(1) expect(findFirstSpy).toHaveBeenCalledWith(expect.objectContaining(defaultQueryConfig)) }) /** * Another test that runs in the suite at a later point in time fails * because instead the object it is trying the result is `undefined` */ test("when event locations are requested it returns events with related locations", async () => { const events = await findManyEventsWithLocations() const locations = events.data.find((e) => e.id === 4)?.locations[0] expect(locations).toEqual({ ...eventLocation, id: 1, eventId: 4, createdAt: expect.any(Date), updatedAt: expect.any(Date) }) })

Sin embargo, si agrego una declaración: findFirstSpy.mockRestore() después de las expectativas de la primera prueba, la segunda prueba pasará muy bien... Pero esto solo es válido si pasa la primera prueba, ya que la prueba no tendrá la oportunidad de "mockRestore" si falla una afirmación anterior.

Siempre podría agregar una "descripción" con un "beforeEach"/"afterEach" alrededor de esta primera prueba, pero creo que esta no debería ser la solución , considerando que jest.spyOn no debería cambiar la implementación a menos que se solicite explícitamente.

¿Sabe alguien por que ha sucedido esto?

Resultado sin findFirstSpy.mockRestore() Resultado sin findFirstSpy.mockRestore()

Resultado con findFirstSpy.mockRestore() Resultado con findFirstSpy.mockRestore()

about 4 years ago · Santiago Gelvez
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!