最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Expected Array but received array in Jest - Stack Overflow

programmeradmin2浏览0评论

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

Share Improve this question edited Feb 1, 2019 at 9:01 skyboyer 23.7k7 gold badges61 silver badges71 bronze badges asked Sep 16, 2017 at 16:22 VesmyVesmy 1,2784 gold badges17 silver badges29 bronze badges 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". – Samuel Neff Commented Sep 1, 2021 at 14:04
Add a comment  | 

2 Answers 2

Reset to default 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

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));
      });
  });
});
发布评论

评论列表(0)

  1. 暂无评论