alayor
alayor

Reputation: 5035

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?

Upvotes: 0

Views: 278

Answers (1)

James
James

Reputation: 82096

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()
   });
})

Upvotes: 1

Related Questions