Expect array argument to have set length

我的梦境 提交于 2021-02-10 17:47:48

问题


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.

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))
})

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

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

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?


回答1:


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.

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

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


来源:https://stackoverflow.com/questions/64198066/expect-array-argument-to-have-set-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!