间谍无法跟踪与摩卡和西农的异步功能测试
Spy could not track on Async function test with Mocha and Sinon
我有isMember函数如下;
function isMember(req, res, next) {
MyService.GetUserAsync(authCookie)
.then(function (user) {
next();
})
.catch(function (err) {
if (err.status === 400) {
return res.redirect("/notAllowed");
}
else {
return next(err);
}
});
}
我的测试如下所示;
beforeEach(function () {
// Overwrite the global timer functions (setTimeout, setInterval) with Sinon fakes
this.clock = sinon.useFakeTimers();
});
afterEach(function () {
// Restore the global timer functions to their native implementations
this.clock.restore();
});
it.only("pass authentication and set authCookie", function (done) {
var user = {
userNameField: "fakeUserName"
};
sinon.stub(MyService, "GetUserAsync").returns(Promise.resolve(user));
var spyCallback = sinon.spy();
var req {};
var res = {};
isMember(req, res, spyCallback);
// Not waiting here!
this.clock.tick(1510);
// spyCallback.called is always false
expect(spyCallback.called).to.equal(true);
done();
});
由于某种原因this.clock.tick
不起作用,spyCallback.called
总是假的。如何实现我的间谍会等到next()
在isMember函数中被调用?
sinon fakeTimers 取代了全局 setTimeout 函数,但您的代码不包含任何超时函数。
您可以使用 setTimeout 函数来延迟期望的执行,然后通过在 setTimeout 中调用 done(( 来解决您的测试。你可以尝试这样的事情:
setTimeout(function () {
expect(spyCallback.called).to.equal(true);
done();
}, 0);
你需要把done()
放在回调中,因为事件循环在javascript中的工作方式。首先执行所有同步代码,然后执行所有挂起的异步任务。
摩卡支持承诺。如果您返回来自it()
的承诺,它将等待。所以,你可以做一些类似的事情
it.only("pass authentication and set authCookie", function (done) {
var user = {
userNameField: "fakeUserName"
};
sinon.stub(MyService, "GetUserAsync").returns(Promise.resolve(user));
var spyCallback = sinon.spy();
var req {};
var res = {};
return isMember(req, res, spyCallback).then(function () {
expect(spyCallback.called).to.equal(true);
});
});
相关文章:
- 在浏览器上显示实习运行程序功能测试的结果
- 使用 Mocha 和 Sinonjs 进行的第一个异步单元测试
- 实习生功能测试和清除 cookie 之前和之后
- 异步功能在预期结果时停止工作
- 硒功能测试结构和实践
- 节点.js的基本功能测试
- 编写功能测试,HTML5 视频标签
- 间谍无法跟踪与摩卡和西农的异步功能测试
- 异步功能完成后执行函数
- 异步功能取决于量角器测试中的外部模块
- 如何将节点 js 的异步功能处理为在节点 js 中同步
- ES7异步功能和promise之间的技术差异
- Redux异步操作测试的目的是什么
- 如何按顺序执行异步Mocha测试(NodeJS)
- 如何使用npm库提供异步集成测试
- 所有节点都是“;回调”;潜在异步功能
- 在PhantomJS中从Ant运行异步QUnit测试
- 为什么这个异步茉莉花测试失败
- 实习功能测试中的多个THEN语句
- 当页面上出现JavaScript错误时,如何在Capybara Webkit的功能测试中失败一步