[英]Node js testing protected routes using mocha chai?
该功能检查路线是否可访问
function isSessionCookieValid(req, res, next) {
if (!isValid(req.session)) {
return res.status(401).json({
isLoggedIn: false
});
}
return next();
}
在另一个文件中,我使用上述函数进行了一个受保护的路由的发布请求
app
.route('/url')
.post(utils.isSessionCookieValid, (req, res, next) => {})
测试部分
问题是我不知道如何模拟isSessionCookieValid ,因为它需要下一个但我无法在我的测试中通过下一个回调:
describe('testing routes', () => {
it('should enter the route body', (done) => {
utils.isSessionCookieValid(req, res, 'next should be here...');
chai.request(server)
.post('/url')
.end(function (error, response, body) {
if (error) {
done(error);
} else {
done();
}
});
});
});
错误:类型错误:下一个不是函数
我将使用sinonjs作为模拟库。 模拟isSessionCookieValid
中间件的实现,让它一直到下一个中间件。
例如
server.ts
:
import express from 'express';
import * as utils from './utils';
const app = express();
const port = 3000;
app.route('/url').post(utils.isSessionCookieValid, (req, res, next) => {
res.sendStatus(200);
});
if (require.main === module) {
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
}
export { app };
utils.ts
:
function isSessionCookieValid(req, res, next) {
if (!isValid(req.session)) {
return res.status(401).json({
isLoggedIn: false,
});
}
return next();
}
function isValid(session) {
return true;
}
export { isSessionCookieValid };
server.test.ts
:
import * as utils from './utils';
import sinon from 'sinon';
import chai, { expect } from 'chai';
import chaiHttp from 'chai-http';
chai.use(chaiHttp);
describe('testing routes', () => {
it('should enter the route body', (done) => {
const isSessionCookieValidStub = sinon.stub(utils, 'isSessionCookieValid').callsFake((req, res, next) => {
next();
});
const { app } = require('./server');
chai
.request(app)
.post('/url')
.end((error, response) => {
if (error) {
return done(error);
}
sinon.assert.calledOnce(isSessionCookieValidStub);
expect(response).to.have.status(200);
done();
});
});
});
单元测试结果:
testing routes
✓ should enter the route body (500ms)
1 passing (510ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 60 | 25 | 25 | 60 |
server.ts | 80 | 50 | 50 | 80 | 12-13
utils.ts | 20 | 0 | 0 | 20 | 2-11
-----------|---------|----------|---------|---------|-------------------
源代码: https : //github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/54462600
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.