[英]Building tests with mocha for async code (request)
我正在尝试在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
回调中吗? 最好的方法是什么?
您应该模拟request
功能。 你可以使用如sinon
该存根(它们提供returns
来定义返回值函数)。
通常,单元测试的想法是分离特定的功能(测试单元),并对其他依赖项进行存根,就像您对request
所做的那样:)
为此,您必须覆盖原始request
对象,例如:
before(function() {
var stub = sinon.stub(someObjectThatHasRequestMethod, 'request').returns(true);
});
在运行测试之后,您应该取消对该对象的存根,以便将来进行这样的测试:
after(function() {
stub.restore();
});
仅此afterEach/after
:)您可以在afterEach/after
或beforeEach/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();
});
您可以在此处找到更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.