使用Sinon
我对Node和Sinon比较陌生。这个应用程序是用Express制作的,我使用的是Mocha,Chai和Sinon。使用Sinon-Chai,我在Express中使用多个回调测试路由,并且无法弄清楚如何检查第二次和后续回调。
我的index.js里面的路由是:
var controller = require('./example.controller');
var validator = require('./example.validator');
var router = express.Router();
router.post('/', validator.create, controller.create);
在我的validator.js中是validator.create,它检查提交的参数:
exports.create = function(req, res, next) {
var valid = true;
var errorMessages = [];
if (req.body.name) {
patt = /[^a-zA-Z0-9 !@#$%^&*()_+\-=\[\]{};':]/g;
if (patt.test(req.body.name)) {
valid = false;
errorMessages.push("Parameter is not alphanumeric");
}
}
if (valid == false) {
return res.status(400).json(errorMessages);
}
next();
}
在我的controller.js中是controller.create,它在DB中创建一个条目:
exports.create = function(req, res) {
return Example.create(req.body)
.then(baseController.respondWithResult(res, 201))
.catch(baseController.handleError(res));
}
Sinon-Chai在我的index.spec.js中测试:
var proxyquire = require('proxyquire').noPreserveCache();
var exampleCtrlStub = {
create: 'exampleCtrl.create',
};
var exampleValidatorStub = {
create: 'exampleValidator.create'
}
var routerStub = {
get: sinon.spy(),
put: sinon.spy(),
patch: sinon.spy(),
post: sinon.spy(),
delete: sinon.spy()
};
var exampleIndex = proxyquire('./index.js', {
express: {
Router() {
return routerStub;
}
},
'./example.controller': exampleCtrlStub,
'./example.validator': exampleValidatorStub
});
describe('POST /api/examples', function() {
it('should route to example.validator.create', function() {
routerStub.post
.withArgs('/', 'exampleValidator.create')
.should.have.been.calledOnce;
});
});
describe('POST /api/examples', function() {
it('should route to example.controller.create', function() {
routerStub.post
.withArgs('/', 'exampleCtrl.create')
.should.have.been.called;
});
});
虽然期望两个测试都通过,但第一个测试(validator.create)通过,但第二个测试(controller.create)失败。我无法找到测试controller.create的方法。
回答如下:在第二次测试中,我们不能使用withArgs
跳过第一个验证器参数。测试失败,因为它正在寻找具有此签名的方法,该方法在源中不存在。
router.post('/', controller.create);
withArgs
始终以第一个和第二个参数开始,等等。因此,解决方案是在测试中包含验证器
routerStub.post
.withArgs('/', 'exampleValidator.create', 'exampleCtrl.create')
.should.have.been.called;
参考:
- https://sinonjs/releases/v7.2.3/mocks/#expectationwithargsarg1-arg2-
希望能帮助到你