Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a HTTP request error using Nock and Request

I have a branch in a function that isn't currently being tested. It's an error handler coming from a request operation (using the node module of the same name). Here is the particular line:

request(url, function (error, response, body) {
  if (error) return cb(error);

Here is the test:

  describe("handles errors", function() {
    it("from the request", function (done) {
    var api = nock('http://football-api.com')
                .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                .reply(500);

    fixture.getFixture(FixtureMock, function (err, fixture) {
      expect(err).to.exist
      done();
    });
  });

Spec fails:

Uncaught AssertionError: expected null to exist

So either sending a 500 status code as a response with no body does not cause an error in the request callback, or I'm testing the wrong thing.

like image 797
goralph Avatar asked Feb 12 '23 20:02

goralph


1 Answers

Use replyWithError from doc:

nock('http://www.google.com')
   .get('/cat-poems')
   .replyWithError('something awful happened');
like image 88
Piotr Fryga Avatar answered Feb 15 '23 12:02

Piotr Fryga