9

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()?

1
  • expect(response.body).any(Array) shouldn't work. .any doesn't exist on the response from expect() but on expect itself. The referenced code gives this error: "TypeError: expect(...).any is not a function". Commented Sep 1, 2021 at 14:04

2 Answers 2

16

You 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

Sign up to request clarification or add additional context in comments.

Comments

1

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));
      });
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.