【发布时间】:2019-07-12 00:08:42
【问题描述】:
我对 Node 和 Sinon 比较陌生。这个应用程序是用 Express 制作的,我使用的是 Mocha、Chai 和 Sinon。使用 Sinon-Chai,我在 Express 中使用多个回调对路由进行 POST 测试,但不知道如何检查第二个和后续回调。
我的 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,它在数据库中创建了一个条目:
exports.create = function(req, res) {
return Example.create(req.body)
.then(baseController.respondWithResult(res, 201))
.catch(baseController.handleError(res));
}
我的 index.spec.js 中的 Sinon-Chai 测试:
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。
【问题讨论】:
标签: node.js mocha.js sinon sinon-chai