I am trying to spyOn a chained function for my socketIO server. The first toSpy
is working fine but I seem to be unable to check the emit
chained function.
Anyone a simple and elegant way to test a chained function in Jest?
const toSpy = jest.spyOn(io, 'to');
const emitSpy = jest.spyOn(io, 'emit');
expect(toSpy).toHaveBeenCalledTimes(1); // 1 times called
expect(emitSpy).toHaveBeenCalledTimes(1); // 0 times called
io.to(id).emit('hello', {
data: data
});
2
Answers
As explained in this similar post, you could provide a mock implementation to your first spy, which will return the object you’re currently testing.
First chained function should return to pass the output from the first function to the second function. So that it goes around till the end of the result manipulation.