2

The callback for request does not seem to get called and the test passes as a result. I presume this may have to do with it being an async call, but I am not sure how to resolve the issue.

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

describe('Test http', function(){                                                                             

it('get', function(){                                                        
  request('http://www.google.com', function (error, response, body) {                                       
    throw new Error("test get")                                                                             
  })                                                                                                        
})                                                                                                          

}) 
Fabian Barkhau
  • 1,349
  • 2
  • 12
  • 31
  • Correct answer can be found here. http://stackoverflow.com/questions/11235815/is-there-a-way-to-get-chai-working-with-asynchronous-mocha-tests – Fabian Barkhau Jan 08 '15 at 20:26

1 Answers1

3

You forgot to add the done-Callback to the test:

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

describe('Test http', function(){                                                                             

    it('get', function(done){                                                        
      request('http://www.google.com', function (error, response, body) {                                       
        throw new Error("test get")
        done();                                                                             
      })                                                                                                        
    })                                                                                                          
}) 

EDIT: If there is no callback, node/mocha will assume the test has finished and stop, before it has parsed the result.

Also, instead of using request directly, I can recommend using supertest: https://www.npmjs.com/package/supertest

BenSower
  • 1,532
  • 1
  • 13
  • 26
  • This will not work as request is async and the function may return faster than the callback is fired thus completing the test – Andrey May 05 '17 at 11:30
  • Hi Andrey, request is async, that is correct, but since I do provide a done-function to the mocha test and only call it in the callback of request and also do not return the request object itself (supertest for example returns standard-conform promises), the test works as expected. – BenSower May 07 '17 at 08:14
  • you are right, I didn't know about this async behavior of mocha tests when done is provided – Andrey May 07 '17 at 15:18