【问题标题】:Building tests with mocha for async code (request)使用 mocha 为异步代码构建测试(请求)
【发布时间】:2016-01-05 00:48:11
【问题描述】:

我正在尝试在 Node.JS 上使用 Mocha 和 Chai 创建单元测试。这是要测试的函数的简化版本:

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)
    });
}

这是我正在尝试编写的测试:

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

request 函数如何返回 true 以使其通过测试?我曾尝试使用承诺,但它也没有奏效。在这种情况下,我应该将 return 语句放在 then 回调中吗?最好的方法是什么?

【问题讨论】:

标签: javascript node.js mocha.js chai


【解决方案1】:

你应该模拟 request 函数。你可以使用例如sinon 存根(它们提供 returns 函数来定义返回值)。

通常 - 单元测试的想法是分离特定功能(测试单元)和存根所有其他依赖项,就像您应该对 request 做的那样:)

为此,您必须覆盖原始 request 对象,例如:

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

在运行测试之后,你应该取消这个对象的存根,以便将来进行类似的测试:

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

仅此而已 :) 您可以同时使用 afterEach/afterbeforeEach/before - 选择更适合您的那个。

还有一点需要注意 - 因为您的代码是异步的,所以您的解决方案可能需要更复杂的测试方式。您可以提供整个 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();
});

您可以在这里找到更多信息:

Mocha - asynchronous code testing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 2012-08-22
    相关资源
    最近更新 更多