有没有办法使用笑话toHaveBeenCalledWith检查参数数组长度?

时间:2020-06-01 13:30:41

标签: javascript typescript jestjs

该函数的调用方式为:

{ items: [1, 2, 3]}

`expect(mockedFunction).toHaveBeenCalledWith(
  expect.objectContaining({
    items: expect.toBeLengthOf(3) // Pseudocode, this function does not exist here
  }),
);`

1 个答案:

答案 0 :(得分:0)

嘲笑函数上的

.mock object上有.calls列表。所以

expect(
  mockedFunction.mock.calls[mockedFunction.mock.calls.length - 1][0].items
).toHaveLength(3);

将在上次调用(items)的第一个(基于0的数字)参数上验证mockedFunction.mock.calls.length - 1属性的长度。

您也可以考虑使用expect.anything()作为占位符:

expect(mockedFunction).toHaveBeenLastCalledWith(
  expect.objectContaining({
    items: [expect.anything(), expect.anything(), expect.anything()]
  })
)

但是我宁愿建议您检查是否可以模拟某些东西(以便返回相同的值一致性)以验证参数本身,而不仅仅是检查内部数组的长度。