javascript 如何在异步测试中测试返回承诺的存根?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16015728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test a stub returning a promise in an async test?
提问by Stefan
How can I test this in a async manner?
如何以异步方式测试这个?
it('Should test something.', function (done) {
var req = someRequest,
mock = sinon.mock(response),
stub = sinon.stub(someObject, 'method');
// returns a promise
stub.withArgs('foo').returns(Q.resolve(5));
mock.expects('bar').once().withArgs(200);
request(req, response);
mock.verify();
});
And here is the method to test.
这是测试的方法。
var request = function (req, response) {
...
someObject.method(someParameter)
.then(function () {
res.send(200);
})
.fail(function () {
res.send(500);
});
};
As you can see I am using node.js, Q (for the promise), sinon for mocking and stubbing and mocha as the test environment. The test above fails because of the async behaviour from the request method and I don't know when to call done() in the test.
如您所见,我使用 node.js、Q(用于承诺)、sinon 用于模拟和存根以及 mocha 作为测试环境。由于请求方法的异步行为,上面的测试失败,我不知道在测试中何时调用 done() 。
采纳答案by David McMullin
You need to call done once all the async operations have finished. When do you think that would be? How would you normally wait until a request is finished?
所有异步操作完成后,您需要调用 done 。你认为那会是什么时候?您通常如何等待请求完成?
it('Should test something.', function (done) {
var req = someRequest,
mock = sinon.mock(response),
stub = sinon.stub(someObject, 'method');
// returns a promise
stub.withArgs('foo').returns(Q.resolve(5));
mock.expects('bar').once().withArgs(200);
request(req, response).then(function(){
mock.verify();
done();
});
});
It might also be a good idea to mark your test as failing in an errorcallback attached to the request promise.
在附加到请求承诺的错误回调中将您的测试标记为失败也可能是一个好主意。
回答by ?ukasz Rzeszotarski
Working solution in Typescript:
打字稿中的工作解决方案:
var returnPromise = myService.method()
returnPromise.done(() => {
mock.verify()
})