jeudi 3 août 2017

Testing for redirection using mocha and chai

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"
  });
}

Aucun commentaire:

Enregistrer un commentaire