Testing for redirection using mocha and chai for expressjs always fails "Uncaught AssertionError: expected redirect with 30{1-3} status code but got 200".
Below is the test for registration page. After successful registration the test code is expecting a redirection to the login page. So the expected response code is 302. But the response code I am getting is 200.
it("Registration Check", done => {
chai
.request(server)
.post("/register")
.send({
name: "pkv",
email: "[email protected]",
password: "pkv",
cpassword: "pkv"
})
.end((err, res, body) => {
res.should.have.status(302);
done();
});
});
The express js code under test is as follows.On successful registration the response is redirected to the login page
if (userInfo.password == userInfo.cpassword) {
if (regexEmail.test(userInfo.email)) {
models.user
.find({
email: userInfo.email
})
.then(user1 => {
if (user1.length) {
res.json({
Err: "Error"
});
console.log("Already Existing user");
} else {
var newuser = new models.user({
name: userInfo.name,
email: userInfo.email,
password: cpass
});
newuser.save(function(err, user) {
if (err) {
console.log("error");
} else {
models.user.find(function(err, response) {
res.redirect("/login");
});
}
});
}
})
.catch(err => {
res.send("Error in database connection");
});
} else {
res.json({
err: "error"
});
}
} else {
res.json({
Response: " Password Mismatch"
});
}
chai-http library automatically follows the redirection path. So the response of your test will be the response of /login. If you want to assert the status code for redirection, you can use redirects(0). Example:
it("Registration Check", done => {
chai
.request(server)
.post("/register")
.send({
name: "pkv",
email: "[email protected]",
password: "pkv",
cpassword: "pkv"
})
.redirects(0)
.end((err, res, body) => {
res.should.have.status(302);
done();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With