I created unit (async) test in Jest. But when I get response from server:
[
{
name: "My name"
},
{
name: "Another name"
}
]
and test it:
test('Response from server', () => {
get('my-url').end(error, response) => {
expect(response.body).toBe(expect.any(Array))
}
})
some error occurs:
Comparing two different types of values. Expected Array but received array.
It's working when I use expect(response.body).any(Array)
. But is there any fix for expect.toBe()
?
I created unit (async) test in Jest. But when I get response from server:
[
{
name: "My name"
},
{
name: "Another name"
}
]
and test it:
test('Response from server', () => {
get('my-url').end(error, response) => {
expect(response.body).toBe(expect.any(Array))
}
})
some error occurs:
Comparing two different types of values. Expected Array but received array.
It's working when I use expect(response.body).any(Array)
. But is there any fix for expect.toBe()
?
2 Answers
Reset to default 16You should use toEqual
(not toBe
) to compare objects and arrays. Use toBe
for scalar data types only. If you like to check the response data type use typeof
operator
I found the answer above is really helpful, this how I implement it in my test
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));
});
});
});
expect(response.body).any(Array)
shouldn't work..any
doesn't exist on the response fromexpect()
but onexpect
itself. The referenced code gives this error: "TypeError: expect(...).any is not a function". – Samuel Neff Commented Sep 1, 2021 at 14:04