使用 supertest 实现测试 API 时添加 expect 方法时出错

问题描述

我正在尝试使用 supertest 测试我的用户端点:

   router.post("/users",async (req,res) => {
  const user = new User(req.body);
  try {
    await user.save();
    const token = await user.generateAuthToken();
    res.status(201).send({ user: user,token: token });
  } catch (e) {
    res.status(400).send(e);
  }
});

我的 user.test.js 看起来像这样:

  const request = require("supertest");
  const app = require("../src/app");

  test("Should signup a new user",async () => {
  await request(app)
    .post("/users")
    .send({
      name: "Andrew",email: "andrew@example.com",password: "MyPass777!",})
    .expect(201);
});

当我运行此代码时出现此错误

enter image description here

但是当我删除 .expect(201) 时一切正常,你能帮我吗?

解决方法

尝试改用这个:

  const {status} = await request(app)
    .post("/users")
    .send({
      name: "Andrew",email: "andrew@example.com",password: "MyPass777!",})
  
  expect(status).toBe(201);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...