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]
To check if a function was called correctly with Jest we use the expect() function with specific matcher methods to create an assertion. We can use the toHaveBeenCalledWith() matcher method to assert the arguments the mocked function has been called with.
To check if a component's method is called, we can use the jest. spyOn method to check if it's called. We check if the onclick method is called if we get the p element and call it.
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.
Mocking Node modules If the module you are mocking is a Node module (e.g.: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.
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))
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With