skip to Main Content

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


  1. 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.

    const toSpy = jest.spyOn(io, 'to').mockReturnThis();
    const emitSpy = jest.spyOn(io, 'emit'); 
    
    expect(toSpy).toHaveBeenCalledTimes(1);
    expect(emitSpy).toHaveBeenCalledTimes(1);
    
    Login or Signup to reply.
  2. 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.

    const toSpy = jest.spyOn(io, 'to').mockReturnValue(<any-value>);
    const emitSpy = jest.spyOn(io, 'emit').mockReturnValue(<any-value>); 
    
    expect(toSpy).toHaveBeenCalledTimes(1); // 1 times called
    expect(emitSpy).toHaveBeenCalledTimes(1); // 1 times called
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search