Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use jests toHaveBeenCalledWith to check arguments array length?

Function would be called with:

{ items: [1, 2, 3]}

expect(mockedFunction).toHaveBeenCalledWith(
      expect.objectContaining({
        items: expect.toBeLengthOf(3) // Pseudocode, this function does not exist here
      }),
    );
like image 354
Eduards Egle Avatar asked Sep 17 '25 23:09

Eduards Egle


1 Answers

.mock object on mocked function has .calls list on it. So

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

will validate length of items property on first(0-based numeration) argument for last time(mockedFunction.mock.calls.length - 1) it has been called.

Also you may consider using expect.anything() as a placeholder:

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

But it may be better to use a mock and return the same values consistently - this will allow you to validate the contents of the array rather than just its length

like image 84
skyboyer Avatar answered Sep 19 '25 13:09

skyboyer