简体   繁体   English

使用Mocha构建测试以获取异步代码(请求)

[英]Building tests with mocha for async code (request)

I am trying to create unit tests with Mocha and Chai on Node.JS. 我正在尝试在Node.JS上与Mocha和Chai创建单元测试。 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? request函数如何返回true才能通过测试? 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? 在这种情况下,我应该将return语句放在then回调中吗? What is the best approach? 最好的方法是什么?

You should mock request function. 您应该模拟request功能。 You could use eg sinon stubs for this (they provide returns function for defining returning value). 你可以使用如sinon该存根(它们提供returns来定义返回值函数)。

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 :) 通常,单元测试的想法是分离特定的功能(测试单元),并对其他依赖项进行存根,就像您对request所做的那样:)

To do so, you have to overwrite original request object, eg : 为此,您必须覆盖原始request对象,例如:

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. 仅此afterEach/after :)您可以在afterEach/afterbeforeEach/before -选择更适合您的一种。

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: 您可以提供完整的request模拟功能,并在返回值时调用done()回调,如下所示:

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 Mocha-异步代码测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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