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: "pkv@pkv.com",
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: "pkv@pkv.com", password: "pkv", cpassword: "pkv" }) .redirects(0) .end((err, res, body) => { res.should.have.status(302); done(); }); });
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.