【发布时间】:2018-05-13 06:14:02
【问题描述】:
我正在尝试对调用 promise 的函数进行单元测试...
使用摩卡,诗乃。我有一个这样的功能块:
我的文件.js:
let OuterDependecy = require('mydep');
function TestFunction(callback) {
OuterDependency.PromiseFunction().then(response => {
//some logic here
}).catch(err => {callback(err)});
在我的测试中,我使用proxyquire 来模拟外部依赖
testfile.js
let proxyquire = require('proxyquire');
let OuterDepStub = {};
let testingFunc = proxyquire('myfile.js', {'mydep': OuterDepStub});
...然后在我的测试块内
let stubCallback = function() {
console.log('Stub dubadub dub'); //note...i can use sinon.spy here instead
};
beforeEach(()=>{
OuterDependency.PromiseFunction = function(arg) {
return new Promise((resolve, reject)=>{
reject('BAD');
});
};
spy = sinon.spy(stubCallback);
});
我的实际测试现在调用主要的“testfunction”
it('Catches Errors, and calls back using error', done => {
TestFunction(stubCallback);
expect(spy).to.have.been.called;
done();
});
我看到存根被调用(控制台日志,因此我不想使用 sinon.spy)但间谍说它没有被调用。并且单元测试失败。
我相信这可能是由于在我的测试运行后承诺正在解决的某种竞争条件......无论如何都会延迟测试直到我的承诺得到解决。
我知道在 angularjs 承诺测试中,有一种方法可以“勾选”承诺,以便在您需要时解决。在nodejs中可能吗?
【问题讨论】:
标签: javascript node.js unit-testing mocha.js