I am trying to run a unit test on my application but the unit test timesout. When I looked deeper into it I found out that it is timing out where the application is trying to set the session data. If I remove the session setting line of code the unit test continues ( but fails because the session data is required ).
// unit test code;
describe('Check if endpoint are reachable', () => {
before(function(done) {
// call /router to generate session;
AGENT.get('/router')
.query(clientData)
.expect(302)
.end((err, res) => {
if (!err) {
done()
} else {
done(err);
}
});
});
// .......
});
// controller code where the session is set;
// .....
req.session.clientData = clientData;
// ....
When I run the code I get the following error: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\\Nedbank\\aa-serverui\\application\\tests\\authorise.js)
But if I comment out the session setting line ( // req.session.clientData = clientData; ) then the test continues to run as expected.
Here is an minimal working example:
app.js
:
const express = require("express");
const session = require("express-session");
const app = express();
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true,
cookie: { secure: true },
}),
);
function controller(req, res) {
const clientData = req.query;
console.log(clientData);
req.session.clientData = clientData;
res.sendStatus(302);
}
app.get("/router", controller);
app.get("/api", (req, res) => {
res.sendStatus(200);
});
module.exports = app;
app.test.js
:
const supertest = require("supertest");
const app = require("./app");
const agent = supertest(app);
const { expect } = require("chai");
describe("Check if endpoint are reachable", () => {
const clientData = { name: "supertest" };
before((done) => {
agent
.get("/router")
.query(clientData)
.expect(302)
.end((err, res) => {
if (!err) {
done();
} else {
done(err);
}
});
});
it("should pass", async () => {
const res = await agent.get("/api");
expect(res.status).to.be.eq(200);
});
});
Integration test result with coverage report:
Check if endpoint are reachable
{ name: 'supertest' }
✓ should pass
1 passing (44ms)
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 96.15 | 50 | 100 | 96.15 | |
app.js | 100 | 100 | 100 | 100 | |
app.test.js | 92.86 | 50 | 100 | 92.86 | 17 |
-------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56526009
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.