Reputation: 127
I have been trying to write a Mocha chai test for a Nodejs API. It was previously written using Supertest. However, in both cases, the test always passed even though I specify wrong expected parameters.
Here is the test function using chai
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.should();
chai.use(chaiHttp);
const app = require("../app");
const user = {
first_name: "Name",
last_name: "Lastname",
email: "email",
password: "password"
};
describe("Registration Test", () => {
it("Responds with status of registration", (done) => {
chai.request(app)
.post('/register')
.send(user)
.end((err,res) => {
if(err) done(err);
res.should.have.status.eq(200);
res.body.should.have.property('success').eq(true);
done(); <------------ Here it doesn't work. It returns For async tests and hooks, ensure "done()" is called error
});
done(); <----------- But here it works
});
});
The API responds with a body with properties success, message and status. But no matter what I write in the chai should checks, the test always passes. Also, when I add the done(); inside the end(), it is not being found, and but when I write it outside the end(), it runs. So I assume my code is never entering the .end().
Upvotes: 1
Views: 1497
Reputation: 127
So, It was a silly mistake that I was doing. I had the server running manually with npm start and the port 5000 was occupied. When I was running the testscript using chai.request(app) the port was already occupied and I only realized that later. However, I wrote the script using async/await like this,
describe("Tests for Doctor and Patient Registration", () => {
it("Existing doctor registation fails", async () => {
const res = await chai
.request(app)
.post("/register")
.set("Content-type", "application/json")
.set("Connection", "keep alive")
.send(user[0]);
expect(res.status).to.equal(200);
expect(res.body).to.have.property("success", false);
expect(res.body).to.have.property(
"message",
"A user with this email already exist, did you forget your password?"
);
});
}
Upvotes: 1
Reputation: 16374
You need to pass the done
parameter and call it only inside the end
function:
it("Responds with status of doctor registration", function (done) {
chai.request(app)
.post('/register')
.send(user)
.end((err,res) => {
should.not.exist(err);
res.should.have.status.eq(200);
res.body.should.have.property('success').eq(true);
});
});
Reference https://www.chaijs.com/plugins/chai-http/#caveat
Upvotes: 0