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?