预期数组,但在 Jest 中收到数组

问题描述 投票:0回答:2

我在 Jest 中创建了单元(异步)测试。但是当我收到服务器的响应时:

[
    {
        name: "My name"
    },
    {
        name: "Another name"
    }
]

并测试它:

test('Response from server', () => {
    get('my-url').end(error, response) => {
        expect(response.body).toBe(expect.any(Array))
    }
})

出现一些错误:

Comparing two different types of values. Expected Array but received array.

当我使用

expect(response.body).any(Array)
时它可以工作。但是
expect.toBe()
有什么解决办法吗?

javascript arrays reactjs jestjs
2个回答
16
投票

您应该使用

toEqual
(而不是
toBe
)来比较对象和数组。仅对标量数据类型使用
toBe
。如果您想检查响应数据类型,请使用
typeof
运算符


0
投票

我发现上面的答案非常有帮助,这就是我在测试中实现它的方式

describe("GET /api/books", () => {
  it("should get all books", () => {
    return request(app)
      .get("/api/books")
      .expect(200)
      .expect("Content-Type", /json/)
      .then((res) => {
        expect(res.body).toEqual(expect.any(Array));
      });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.