describe("/test" , ()=> {
// separate class 2
class2 = {
// function that i wanna stub
hi: function () {
return "hi";
}
}
// separate class 1
class1 = {
// function that i have stubbed and tested
method1: function() {
return new Promise((resolve, reject) => {
resolve(num);
})
}
}
// method that i will execute
var parent= function (){
class1.method1().then(()=>{
class2.hi();
})
}
// the test
it("should stub hi method",()=>{
var hiTest = sinon.stub(class2, 'hi').resolves(5);
var method1Test = sinon.stub(class1 , 'method1').resolves(5);
// this start the execution of the promise with then call
parent();
// this works fine and test pass
expect(method1Test.calledOnce.should.be.true);
// this doesn't work although i executed the function
expect(hiTest.calledOnce.should.be.true);
})
})
我想做的是正确测试hi方法 ..因为当我测试方法是否执行一次
虽然我在承诺的调用中执行了它但是没有显示它并且它使被调用的测试失败
答案 0 :(得分:1)
这里的问题是你正在测试代码,就好像它是同步的,当它不是(正如你使用Promise
时)。
为了能够正确测试,我们需要能够挂钩以parent
调用class1.method1
开头的承诺链。
我们可以通过返回调用class1.method1
返回的承诺来做到这一点。
就测试本身而言,我们需要确保Mocha
在等待承诺时不会结束测试,因此我们使用done
回调参数来告诉Mocha
当我们认为测试结束时。
describe("/test", ()=> {
class2 = {
hi: function () {
return "hi";
}
}
class1 = {
method1: function() {
return new Promise((resolve, reject) => {
resolve(num);
})
}
}
var parent = function (){
return class1.method1().then(()=>{
class2.hi();
})
}
it("should stub hi method", (done)=> {
var hiTest = sinon.stub(class2, 'hi').returns(5);
var method1Test = sinon.stub(class1 , 'method1').resolves(5);
parent().then(() => {
expect(method1Test.calledOnce.should.be.true);
expect(hiTest.calledOnce.should.be.true);
done();
});
})
})