55

I'm trying this:

expect(AP.require).toBeCalledWith('messages', () => {})

where AP.require is a mocked function that should receive a string and a function as the second argument.

Test fails with the message:

Expected mock function to have been called with:
  [Function anonymous] as argument 2, but it was called with [Function anonymous]

2 Answers 2

112

To assert any function, you can you use expect.any(constructor):

So with your example it would be like this:

expect(AP.require).toBeCalledWith('messages', expect.any(Function))
3
  • 3
    Probably obvious for some, but still worth pointing out you can use any other constructor (e.g. Number, Object, etc.)
    – Simone
    Commented Dec 18, 2020 at 12:10
  • There is also expect.anything() if that second argument is optional. Commented Mar 18, 2021 at 19:40
  • @Rohmer If that second argument is optional, you should probably add an additional test.
    – Koen.
    Commented Mar 18, 2021 at 20:06
24

The problem is that a function is an object and comparing objects in JavaScript will fail if they are not the same instance

() => 'test' !== () => 'test'

To solve this you can use mock.calls to check the parameters seperataly

const call = AP.require.mock.calls[0] // will give you the first call to the mock
expect(call[0]).toBe('message')
expect(typeof call[1]).toBe('function')
1
  • 2
    This answer helped me, thanks Andreas. I think the first line should be const call = AP.require.mock.calls[0] Commented Dec 3, 2017 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.