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

瘦欲@ 提交于 2019-12-05 01:27:09

You're mocking the component with a string as the second argument. That's unusual, as the jest.mock function expects a function as a second argument. The string may work for your test (depending on how it is rendered) but it's undefined behavior in Jest's documentation and is probably what is causing your problem. Instead pass a function that returns a component. Here's one that passes a simple functional component that just passes the name back:

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

After playing around with it, I realized I had the syntax wrong for my returned component. Mocking it like this works:

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

Mocking it like this doesn't (this is what I was doing):

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

The warning even told me the issue, but I misinterpreted it:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of Termination.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!