Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jest, how can I check that an argument to a mocked function is a function?

Tags:

node.js

jestjs

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] 
like image 735
Azeez Olaniran Avatar asked Oct 23 '17 13:10

Azeez Olaniran


People also ask

How do you check if a mocked function was called?

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.

How do you check if a function is in Jest?

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.

What is function Mockconstructor Jest?

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.

What is __ mocks __ in Jest?

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.


2 Answers

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)) 
like image 126
Koen. Avatar answered Sep 21 '22 18:09

Koen.


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') 
like image 25
Andreas Köberle Avatar answered Sep 20 '22 18:09

Andreas Köberle