【问题标题】:Is there a way to use jests toHaveBeenCalledWith to check arguments array length?有没有办法使用 toHaveBeenCalledWith 来检查参数数组长度?
【发布时间】:2020-06-02 19:48:48
【问题描述】:
函数将被调用:
{ items: [1, 2, 3]}
`expect(mockedFunction).toHaveBeenCalledWith(
expect.objectContaining({
items: expect.toBeLengthOf(3) // Pseudocode, this function does not exist here
}),
);`
【问题讨论】:
标签:
javascript
typescript
jestjs
【解决方案1】:
.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()]
})
)
但我宁愿建议检查您是否可以模拟某些东西(以便返回相同的值一致性)来验证参数本身,而不仅仅是检查内部某处的数组长度。