gpt4 book ai didi

jestjs - 期望数组参数具有设置长度

转载 作者:行者123 更新时间:2023-12-04 08:48:20 27 4
gpt4 key购买 nike

我对 Jest 有点陌生,所以如果这是一个明显的答案,请原谅我,但在滚动浏览文档后我找不到答案。

我有一个函数 (funcA),它将一个不同长度的数组传递给另一个函数 (funcB),具体取决于 funcA 的参数收到。我正在尝试根据我提供给 funcA 的参数来测试传递给 funcB 的数组的长度是否正确。我并不关心数组的内容,只是它有一定的长度。这是我目前的尝试:

// Modules
const funcA = require('./funcA')

// Mock
const funcB = jest.fn(pairs => {
return pairs[0]
})

// Test
test('Should pass array of 3623 length', () => {
const result = funcA(75)

expect(result).toBeInstanceOf(Object)
expect(funcB).toHaveBeenCalledWith(expect.any(Array).toHaveLength(3623))
})

我想尝试使用 any()如果可以,但以下测试会导致错误:

TypeError: expect.any(...).toHaveLength is not a function

即使我将 expect.any(...) 包装在另一组括号中,我也会收到相同的错误。有什么方法可以实现我想要的吗?

最佳答案

只断言数组长度而忽略数组内容的测试没有什么值(value)。越具体越好。如果需要特定的数组,可以将其指定为夹具。

此断言无法工作,因为 toHaveBeenCalledWith 应该是预期结果,并且不能包含另一个断言 toHaveLength

为了用包含任何元素的数组断言 toHaveBeenCalledWith,它应该是:

expect(funcB).toBeCalledWith(Array(3623).fill(expect.anything()))

另一种选择是直接断言参数:

expect(funcB).toBeCalledWith(expect.any(Array))
expect(funcB.mock.calls[0][0]).toHaveLength(3623))

关于jestjs - 期望数组参数具有设置长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64198066/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com