2
votes

The following test is not working with mocha-chai, it is able to to get the input request but throws the error message.

 it('/hb  : ', function (done) {
            return chai.request(app)
                .post('/hb')
                .send({"a":1 })
                .then(function (res) {
                    expect(err).to.be.null;
                    expect(res).to.have.status(200);
                    // { ah: { rt: [Object] }, ad: { mojo: 1 } } }
                    //console.log("CAlling DOne ........... +");
                    done();
                }, function (err) {
                    //console.log(err);
                    throw err;
                });
});

Output:

Web Requests : /hb : : Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

2

2 Answers

2
votes

The functions that chai-http adds to chai return promises. In your code you return the promise, which is good. However, you also declare your test to take the a parameter: function (done). This would be fine if you did not return the promise, but returning the promise is really the better mechanism here. When you declare your test to take a parameter, Mocha ignores the return value from the test, and so the promise is ignored. So just remove your use of done.

Here's an example that reproduces the error you had in your original code with err being undefined in the function you pass to then.

'use strict';
var app = require('./server');
var chai = require('chai');
chai.use(require('chai-http'));

var expect = chai.expect;

it('/hb', function () {
    return chai.request(app)
        .post('/hb')
        .send({a: 1})
        .then(function (res) {
            expect(err).to.be.null;
            expect(res).to.have.status(200);
        });
});

If the server returns a 200 status, then you'll get this on the console:

  1) /hb

  0 passing (26ms)
  1 failing

  1)  /hb:
     ReferenceError: err is not defined
      at test.js:13:20

If the server returns a 400 status, the output would be:

  1) /hb

  0 passing (24ms)
  1 failing

  1)  /hb:
     Error: Bad Request
      at Test.Request.callback (node_modules/superagent/lib/node/index.js:792:17)
      at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/index.js:990:12)
      at endReadableNT (_stream_readable.js:913:12)
0
votes

you need to add following:

.set('content-type', 'application/x-www-form-urlencoded')

you can reference this question over Post request via Chai