So according to Jest documentation and multiple posts on the web and so was my belief, using jest.spyOn(foo, "bar") would wrap the specified function with methods that allow us to perform assertions over foo.bar without changing the actual implementation. To change the implementation we would need to use mockImplementation etc...
However, I am experiencing an issue where using jest.spyOn(foo, "bar") is clearly behaving like a jest.fn() mock.
/**
* 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)
})
})
However, if I add a statement: findFirstSpy.mockRestore() after the expectations of the first test the second test will pass fine and dandy... But this is only valid if the first test passes since the test will not get a chance to "mockRestore" if a previous assertion fails.
I could always add a "describe" with a "beforeEach"/"afterEach" around this first test, but I think this should not be the solution, considering jest.spyOn should not change implementation unless explicitly requested.
Does anybody know why this happens?