我在 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()
有什么解决办法吗?
您应该使用
toEqual
(而不是 toBe
)来比较对象和数组。仅对标量数据类型使用 toBe
。如果您想检查响应数据类型,请使用 typeof
运算符
我发现上面的答案非常有帮助,这就是我在测试中实现它的方式
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));
});
});
});