before(function _before(){
this.spyLog = sinon.spy(this.myOBJ.log, 'warn');
});
after(function _after(){
this.spyLog.restore();
});
it('should', sinon.test(function() {
const stubFindOne = this.stub(this.myOBJ, 'findOne');
stubFindOne.returns(bluebird.reject(new Error('Should have failed')));
this.myOBJ.toBeTestedFunction({});
setTimeout(function _expect() {
console.log('++++++++++++ 1 ++++++++++++++++++++++++++++++++++++++++');
console.log('this.spyLog', this.spyLog.args);
expect(this.spyLog.args[0][0].toString()).to.be.equal('Error: Should have failed');
console.log('++++++++++++ 2 ++++++++++++++++++++++++++++++++++++++++');
}, 100);
}));
爲什麼_expect
功能無法運行?謝謝
UPDATE 試過以下代碼,但得到了Error: timeout of 2000ms exceeded
。我認爲這是因爲done
不叫。我需要this.myOBJ.toBeTestedFunction({});
完成運行,然後運行預期。如何修復代碼?
it('should', sinon.test(function(done) {
const stubFindOne = this.stub(this.myOBJ, 'findOne');
stubFindOne.returns(bluebird.reject(new Error('Should have failed')));
this.myOBJ.toBeTestedFunction({});
setTimeout(function _expect() {
console.log('++++++++++++ 1 ++++++++++++++++++++++++++++++++++++++++');
console.log('this.spyLog', this.spyLog.args);
expect(this.spyLog.args[0][0].toString()).to.be.equal('Error: Should have failed');
console.log('++++++++++++ 2 ++++++++++++++++++++++++++++++++++++++++');
done();
}, 100);
}));
UPDATE
我以下代碼工作。但如何改善呢?
it('should', sinon.test(function() {
const stubFindOne = this.stub(this.myOBJ, 'findOne');
stubFindOne.returns(bluebird.reject(new Error('Should have failed')));
return new bluebird.Promise((resolve, reject) => {
this.myOBJ.tobetestedFunction();
resolve();
})
.delay(1000)
.then(() => {
expect(this.spyLog.args[2][0].toString()).to.be.equal('Error: Should have failed');
});
}));
試圖評估,但得到了'錯誤:超時超過2000毫秒' – BAE
您能否介紹一下關於「這不是一個好計劃」的更多細節? – BAE
是的。我同意。但是這是我爲現有代碼編寫測試的工作,現在我不應該改變它。如何爲異步函數編寫適當的單元測試? – BAE