[英]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.