我有一个中间件,它根据传递的参数检查用户身份验证。中间件使用一个实现promises的模型来查找并返回要设置为请求参数的用户。
问题是,在运行测试时,如果断言失败,测试会超时,大概是因为失败的断言抛出的异常无法由Mocha处理。
我在next()函数中执行断言 - 当测试未提供密钥时,它正常工作,我假设因为它不是在promise的上下文中运行。
# Authenticator
var Authentication = function(model) {
this.model = model;
};
Authentication.prototype.resolve = function(customerKey) {
return this.model.authenticate(customerKey);
};
module.exports = function(model) {
return function(req, res, next) {
if (!req.query.hasOwnProperty('customerKey')) {
throw new Error('There was no auth key provided');
}
var auth = new Authentication(model);
auth.resolve(req.query.customerKey)
.then(function(customer) {
if (!customer) {
throw new Error('There was no customer found with the supplied auth key');
}
req.params.auth = customer;
})
.done(next, next);
};
};
# Test
var should = require('chai').should(),
authentication = require('src/api/middleware/authentication'),
model = require('src/models/customer'),
auth = authentication(model);
describe('middleware/authentication', function() {
it('should set the user to the request if the customerKey is valid', function(done) {
var request = {
query: {
customerKey: 'thisIsValid'
},
params: {}
};
var response = function() {
// This is a no-op
};
var next = function(response) {
response.should.be.instanceOf(String); // If this assertion fails, the test times out and doesn't work
response.should.have.property('name');
response.name.should.be.a('string');
done();
};
// Actually calls the auth
auth(request, response, next);
});
});