AHaberl AHaberl - 5 months ago 17
Node.js Question

Request is not executed during mocha integration test

Before exchanging an API, I want to secure the client (which uses the API) with integration tests to make sure that the new API delivers the same results as the old one and the client still works as expected. Therefor I have written several integration tests for the respective client methods. These client methods use request to query the API.

I am then using mocha to execute the tests. Within the tests it now seems like the requests are not executed at all.

I have made a simple example to show my problem:

var request = require('request');
var assert = require('chai').assert;

describe('test', function(){
it('request-test', function(done){
var responseBody;
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
responseBody = body;
}
});
done();
assert.notEqual(responseBody, undefined);
});
});


In this example the console.log is never executed and the test always fails in the assertion.

Answer

There is issue with the placement of done(). done() is used for testing asynchronous code.

Use it within the callback to have proper execution of test case.

var request = require('request');
var assert = require('chai').assert;

describe('test', function(){
   it('request-test', function(done){
      var responseBody;
      request('http://www.google.com', function (error, response, body) {
          if (!error && response.statusCode == 200) {
              responseBody = body;
              assert.notEqual(responseBody, undefined);
              done();   
          }                   
      });
   });
});