我试图使用sinon来验证程序中的某些步骤是否已执行,我不知道执行步骤的确切时间,我只想确认方法I' m测试将调用给定的函数。
以下是我目前的工作:
describe('Native calls handling', function() {
var ctrl;
beforeEach(function() {
ctrl = new EthernetController($placeholder, notifications, null, nav);
});
// What I currently do
it('Should perform internet check on `Connected` event', function(done) {
var errorTimeout = setTimeout(function() {
internetCheck.restore();
done(new Error('Assertion failed, internetCheck was not executed'));
}, 1500);
var internetCheck = sinon.stub(ctrl, 'internetCheck', function() {
clearTimeout(errorTimeout);
internetCheck.restore();
done();
return Promise.resolve(true);
});
app.notify('system:ethernet:connected');
});
// Functionality I'm looking for
it('Should perform internet check on `Connected` event', function(done) {
var internetCheck = sinon.stub(ctrl, 'internetCheck', function() {
return Promise.resolve(true);
});
// Fail the test if the function is not called within $ ms
// Also restore the stub
internetCheck.cancelationTime = 1500;
// Trigger the assertion after/if the function is called
internetCheck.whenCalled(function(params...) {// assertion })
.timedOut(done);
app.notify('system:ethernet:connected');
});
});
Connected
事件将触发异步程序,最终将执行internetCheck
是否有类似于我正在寻找的东西
编辑: 对我来说真正的问题是方法在内部使用promises但返回 void 所以我没有简单的方法来找出程序何时完成。 我会回答一下我最后做的事情
答案 0 :(得分:0)
我偶然发现Codeigniter DB function call是 node.js 。由于我们的项目使用了Q promises,但是borwser中没有process
对象,我自己编译了。
它不涉及 sinon ,但它解决了我的问题:
/**
* Make testing of Q promises as synchronous code
* Calling process.apply() will complete all pending Q promises
*/
(function(global) {
'use strict';
var _queue = [];
// Fake process object
global.process = {
// process.toString() is used internally by Q (v1.4.1) to recognize environment
// We are lying to it to exploit it's inner workings
toString: function() {
return '[object process]';
},
nextTick: function(cb) {
_queue.push(cb);
},
apply: function() {
console.info('Flushing pending tasks');
var head;
while (head = _queue.shift()) {
head();
}
}
};
})(window);
然后是测试用例:
describe('Native calls handling', function() {
var ctrl;
beforeEach(function() {
ctrl = new EthernetController($placeholder, notifications, null, nav);
});
it('Should perform internet check on `Connected` event', function() {
var internetCheck = sinon.stub(ctrl, 'internetCheck');
internetCheck.returns(Q.resolve(true));
app.notify('system:ethernet:connected');
process.apply();
expect(internetCheck).toHaveBeenCalled();
});
});