How do you mock a reaction component with Jest that has props?

There should be an easy way to do this, but I cannot find the documentary syntax anywhere. I have a React component with a prop that I would like to mock Jest as follows:

jest.mock('./common/MultiSelect', 'MultiSelect'); 

This works, except that I end up with a React warning cluttering my test results:

Warning: Unknown scroll options by tag. Remove this support from the element.

The component that I am mocking has the prop option, and I really don’t care how it is done, since I can mock it so that it does not give a warning? I tried using React.createElement in mock and returned an array with the name of the element and the arguments of props to the end.

The component I want to make fun of is used as follows:

 <MultiSelect options={['option 1', 'option 2']} /> 
+10
source share
2 answers

You are mocking a component with a string as the second argument. This is unusual since the jest.mock function expects the function as the second argument. The string may work for your test (depending on how it is displayed), but it does not determine the behavior in the Jest documentation and is probably the cause of your problem. Instead, pass a function that returns a component. Here is one that passes a simple functional component that just passes the name back:

jest.mock('./common/MultiSelect', () => () =><span>MultiSelect</span>);

+7
source

After playing with it, I realized that for my returned component, I used the syntax incorrectly. Mocks it:

 jest.mock('../../../../../common/components/MultiSelect/MultiSelect', () => () => <div />); 

Mocking this is not the case (this is what I did):

 jest.mock('../../../../../common/components/MultiSelect/MultiSelect', () => <div />); 

The warning even informed me of the problem, but I misinterpreted it:

Warning: React.createElement: type is invalid - a string is expected (for built-in components) or a class / function (for composite components), but received: an object. Check out the Termination rendering method.

+2
source

Source: https://habr.com/ru/post/1268613/


All Articles