今天我遇到了一个问题,我通过了本应该失败的测试。使用Sinon的一些错误的存根方法无法正确地存根回调。我本来希望执行失败,但它通过了测试,但是它提前停止执行,因为我的测试消息在错误的存根方法调用时退出了登录到控制台。
我的代码类似于以下内容:
exports.myFunc = function (req, res) {
var innerFunc = function(callback) {
fs.exists('some/dir', function (exists) {
if (!exists) { // handle error }
else {
logger.log('this prints to the console');
utilModule.stubbedMethod('some/dir', callback);
}
});
};
logger.log('this also prints to the console');
innerFunc(function (err, value) {
logger.log('this does not print to the console');
if (err) {
logger.log('this does not print to the console');
res.status(500).send(err);
} else {
logger.log('this does not print to the console, either');
res.send('success');
}
});
});
// This is the tests, now:
var app = require('../app'),
mod = require('../lib/myModule'),
request = require('supertest'),
chai = require('chai'),
sinon = require('sinon');
describe('For module myModule', function () {
...
describe('#myFunc', function () {
var fs = require('fs'),
util = require('../lib/utilModule');
describe('Happy path', function () {
var expectedResult = "expected";
before(function() {
sinon.stub(fs, 'exists').yields(true, null);
sinon.stub(mod, 'stubbedMethod').yield("some value");
// the above is wrong and should have been yield(null, null, "some value")
});
after(function () { fs.exists.restore(); mod.stubbedMethod.restore(); });
it('Replies with the right value and status 200', function () {
request(app).get('/url').expect(200, 'success').end(function(err, res) {
if (err) throw err;
}
});
});
});
为什么这个测试通过了,有没有办法防止它通过?