Search code examples
node.jsunit-testingpromisejestjseventemitter

Unit test promise result inside Event Listener in Node


I have the following code that I want to test.

emitter.on("request", function(req, res) {
    mock_finder.getMockedResponse().then((mockedResponse) => {
       res.end(mockedResponse);
    });
  });

Then, I have this unit test.

it("should return mocked response", () => {
    // given
    const mockedResponse = {
      success: true
    };
    mock_finder.getMockedResponse.mockImplementation(() => Promise.resolve(mockedResponse));
    const res = {
      end: jest.fn()
    }
    // when
    emitter.emit('request', req, res);
    // then
    expect(res.end).toHaveBeenCalledWith(mockedResponse);
  });

This test is not working because res.end(mockedResponse); is executed after the test finishes.

How can I test the promise response after an event is called?


Solution

  • Given there's no real async code going on here, you can verify the result on the next tick:

    if('should return mocked response', done => {
       ...
       emitter.emit('request', req, res);
       process.nextTick(() => {
         expect(res.end).toHaveBeenCalledWith(mockedResponse);
         done()
       });
    })