Monday, 19 July 2021

test for nested object in a custom matcher

I would like to test, if a function is called with a specific nested object.

myFunction({ variables: { input: { id: 12345, foo: 'bar' }}})

So this is my expect in the test:

expect(myFunction).toHaveBeenCalledWith(
  expect.objectContaining({
    variables: expect.objectContaining({
      input: expect.objectContaining({
        id: 12345,
        foo: 'bar'
      })
    })
  })
)

I like this one as the error message in case of a failing test is very useful.

As I have to test many times for the object, I would like to extract the toHaveBeenCalledWith into a own function or even better build a custom matcher.

Just putting the repeatable part into a own function is not correct:

export const parameterFunctionCall = (param: object, name: string = "input"): void => {
  expect.objectContaining({
    variables: expect.objectContaining({
      [name]: expect.objectContaining(param)
    })
  })
}

expect(myFunction).toHaveBeenCalledWith(
  parameterFunctionCall({
    id: 12345,
    foo: 'bar'
  })
)


from test for nested object in a custom matcher

No comments:

Post a Comment