我如何告诉Supertest不要发送带有请求的Cookie?

时间:2019-01-24 14:08:15

标签: express cookies supertest

现在可以通过Mocha和Supertest在Node上

学习测试。

问题

我想测试用户注册以及该用户是否已经存在于数据库中。 但是在检查之前,我还要检查res.cookie.id。因为如果设置了此选项,我将以不同的消息(例如User is already signed in)回应 但是在测试中,我想摆脱cookie,因为我什至从未接触过检查用户是否在数据库上的中间件。

这是我的测试现在的样子:

describe("Controller function to check if user exists", () => {
  beforeEach(done => {
    request(app)
      .post("/user/register")
      .send({
        username: "dhuber126",
        email: "dhuber126@gmail.com",
        password: "asfsdf4441!!!"
      })
      .set("Accept", "application/json")
      .unset("Cookie")
      .then(res => done());
  });

  it("should return with 400 and that the user already exists", done => {
    request(app)
      .post("/user/register")
      .send({
        username: "dhuber126",
        email: "dhuber126@gmail.com",
        password: "asfsdf4441!!!"
      })
      .set("Accept", "application/json")
      .set("set-cookie", null)
      .expect(400, '"User is already existing in the database"', done);
  });
});

测试失败,如下所示:

  

错误:预期为'“用户已在数据库中”“响应正文,得到了>'”用户已登录“       +预期-实际

因此,用于检查用户是否已登录的中间件将首先运行,而不会进入第二个中间件。我认为解决此问题的唯一方法是在请求中排除cookie,因此后端请参见req对象上没有req.cookie.id

我该如何实现?我尝试了几件事:

我尝试了什么

我尝试了.set("cookie", null).set("set-cookie", null" 我也尝试了unset("cookie"),因为它是supertest中request对象上的一种方法(但未在文档中列出)。 但是没有任何效果。

我该如何实现?

这是我的2个控制器中间件:

isAlreadyLoggedIn: async (req, res, next) => {
    const { id } = res.cookie;
    if (id) {
      res.status(400).json("User is already signed in");
      return;
    }
    next();
  },
  isAlreadyExisting: async (req, res, next) => {
    const user = await User.findOne({ email: req.body.email });

    if (user) {
      res.status(400).json("User is already existing in the database");
      return;
    }

    next();
  },

谢谢!

0 个答案:

没有答案