eugef / node-mocks-http

Mock 'http' objects for testing Express routing functions
Other
753 stars 133 forks source link

Expect fail inside response.on end gets caught in a catch block #199

Closed sbland closed 4 years ago

sbland commented 4 years ago

If response.on('end'... contains an expect()... statement that fails. The error is caught in the catch function within the request function and causes the async test to timeout rather than give correct error.

var httpMocks = require('node-mocks-http');

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const resetData = async () => {
  await timeout(500);
}

const fakeDb = async() => {
  await timeout(500);
  return "demo db";
}

const dbRequest = async (req, res) => {
  await timeout(500);

  fakeDb()
  .then(() => {
    res.send({message: 'hello world'});
  })
// COMMENTING OUT BELOW CATCH RESOLVES ISSUE
// -------------------------------------------------
  .catch(() => {
    console.log("failed");
    res.send({message: 'Failed'});
  });
// -------------------------------------------------
}

describe('demo this', () => {
  afterAll(() => {
    return resetData();
  });
  describe('Call DB request', () => {
    const request = httpMocks.createRequest({});

    const response = httpMocks.createResponse({
      eventEmitter: require('events').EventEmitter,
    });

    it('Successfully Calls DB request', (done) => {
      response.on('end', () => {
        data = response._getData();
        // BELOW failed expect is caught in above catch statement
        expect(data).toEqual();
        done();
      });
      dbRequest(request, response)
    }, 3000);
  });
});

Test fails with following error: Timeout - Async callback was not invoked within the 3000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 3000ms timeout specified by jest.setTimeout.Error:

github-actions[bot] commented 4 years ago

Stale issue message