期望数组参数具有设置的长度 [英] Expect array argument to have set length

查看:51
本文介绍了期望数组参数具有设置的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Jest的新手,所以如果这是一个明显的答案,请原谅我,但在浏览文档后找不到答案.

I'm a bit of a newbie to Jest so please forgive me if this is an obvious answer but I cannot find an answer after scrolling through the docs.

我有一个函数(funcA),该函数根据funcA接收到的参数将不同长度的数组传递给另一个函数(funcB).我试图根据我提供给funcA的参数来测试传递给funcB的数组的长度是否正确.我对数组的内容不是很在意,只是它有一定的长度.这是我目前的尝试:

I have a function (funcA) which passes an array of different lengths to another function (funcB) dependent on the arguments that funcA receives. I'm attempting to test the the length of the array that is passed to funcB is correct based on the arguments that I give to funcA. I am not that bothered about the contents of the array, just that it has a certain length. This is my current attempt:

// 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() 测试结果错误:

I wanted to try to use any() if I could but the following test results in the error:

TypeError:Expect.any(...).toHaveLength不是函数

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

I get the same error even if I wrap the expect.any(...) in another set of parentheses. Is there any way to achieve what I want?

推荐答案

仅声明数组长度而忽略数组内容的测试没有什么价值.具体越好.如果需要特定的数组,则可以将其指定为灯具.

A test that asserts only array length and ignores array contents is of little value. The more specific it is, the better. If specific array is expected, it can be specified as a fixture.

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

This assertion cannot work because toHaveBeenCalledWith is supposed to be expected result and cannot contain another assertion, toHaveLength.

为了使用包含任何元素的数组声明toHaveBeenCalledWith,它应该是:

In order to assert toHaveBeenCalledWith with an array with any elements, it should be:

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

另一种选择是直接声明该参数:

Another option is to assert the argument directly:

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

这篇关于期望数组参数具有设置的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆