简体   繁体   English

使用 mocha 和 chai 测试重定向

[英]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".使用 mocha 和 chai for expressjs 测试重定向总是失败“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 .所以预期的响应代码是302 But the response code I am getting is 200 .但是我得到的响应代码是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测试中的express js代码如下,注册成功后响应重定向到登录页面

   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. chai-http库自动跟随重定向路径。 So the response of your test will be the response of /login .所以你的测试的响应将是/login的响应。 If you want to assert the status code for redirection, you can use redirects(0) .如果要断言重定向的状态代码,可以使用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(); }); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM