我正在测试中间件功能并收到错误:
TypeError:***不是函数
我的test.js
describe('Login', () => {
it('it must check that function create the token', () => {
const req = {
body: { email: 'user@mail.com', password: '12345' }
}
const res = { locals: sinon.spy() }
return authMiddleware.login(req, res) // authMiddleware.test.js:41
.then(res => {
expect(res.locals.token).to.not.be.undefined;
})
.catch(err => console.log(err));
});
});
和middleware.js
module.exports = User => ({
login(req, res, next) {
if (!req.body.email || !req.body.password) return res.sendStatus(401);
return User.findOne({ email: req.body.email })
.then(user => {
if (!user) return res.sendStatus(401);
if (!user.isValidPassword(req.body.password)) return
res.sendStatus(401);
let payload = { id: user.id };
let token = jwt.encode(payload, config.auth.jwtSecret);
res.locals.token = token;
next();
})
.catch(next);
},
});
错误:
TypeError: authMiddleware.login is not a function
at Context.it (test/api/middleware/authMiddleware.test.js:41:35)
我做错了什么?
答案 0 :(得分:0)
您的 middleware.js
文件导出一个接受 User
参数的箭头函数。此函数的返回值是一个对象,该对象具有带有快速中间件签名的 login
方法。
您应该像这样调用 login
中间件:
const { login: loginMiddleware } = require('./middleware')(req.body);
loginMiddleware(req, res, next);