简体   繁体   中英

Building tests with mocha for async code (request)

I am trying to create unit tests with Mocha and Chai on Node.JS. Here is a simplified version of the function to test:

router.cheerioParse = function(url, debugMode, db, theme, outCollection, _callback2) {
    var nberror = 0;
    var localCount = 0;
    console.log("\nstarting parsing now :  " + theme);
    request(url, function(error, response, body) {
        //a lot of postprocessing here that returns 
        //true when everything goes well)
    });
}

Here is the test I am trying to write:

describe('test', function(){
    it('should find documents', function(){
        assert(  true ==webscraping.cheerioParse("http://mytest.com,   null, null, null ,null,null ));
    });
})

How can the request function return true to have it passed to the test? I have tried to use promises but it didn't work either. In this case should I put the return statement in the then callback? What is the best approach?

You should mock request function. You could use eg sinon stubs for this (they provide returns function for defining returning value).

In general - the idea of unit tests is to separate particular function (unit of test) and stub every other dependency, as you should do with request :)

To do so, you have to overwrite original request object, eg :

before(function() {
  var stub = sinon.stub(someObjectThatHasRequestMethod, 'request').returns(true);
});

And after running tests you should unstub this object for future tests like that:

after(function() {
  stub.restore();
});

And that's all :) You could use both afterEach/after or beforeEach/before - choose the one that suits you better.

One more note - because your code is asynchronous, it is possible that your solution might need more sophisticated way of testing. You could provide whole request mock function and call done() callback when returning value like this:

it('should find documents', function(done) {
  var requestStub = sinon.stub(someObjectThatHasRequestMethod, 'request',
    function(url, function (error, response, body) {
      done();
      return true;
  }
  assert(true === webscraping.cheerioParse("http://mytest.com,   null, null, null ,null,null ));
  requestStub.restore();
});

You could find more info here:

Mocha - asynchronous code testing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM