您如何使用带有道具的Jest模拟React组件? [英] How do you mock a react component with Jest that has props?

查看:147
本文介绍了您如何使用带有道具的Jest模拟React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须有一种简单的方法来执行此操作,但是我无法在任何地方找到文档化的语法.我有一个React组件,上面有一个我想在Jest中模拟的道具:

There has got to be a simple way to do this, but I can't find documented syntax anywhere. I have a React component with a prop that I'd like to mock in Jest like this:

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

那行得通,除了我最终得到一个React警告,使我的测试结果变得混乱:

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

警告:标签上的未知道具options.从元素中删除该道具.

Warning: Unknown prop options on tag. Remove this prop from the element.

我正在模拟的组件确实具有一个选项道具,而且我真的不在乎它的呈现方式,那么我如何以一种不会发出警告的方式来模拟它呢?我试过在模拟中使用React.createElement,并返回一个数组,其中包含元素名称和props参数,没有结束.

The component I'm mocking does have an options prop, and I really don't care how it's rendered, so how can I mock it in such a way it will not throw the warning? I've tried using React.createElement in the mock, and returning an array with element name and props arguments to no end.

我要模拟的组件是这样使用的:

The component I want to mock is used like this:

<MultiSelect
options={['option 1', 'option 2']}
/>

推荐答案

您正在模拟使用字符串作为第二个参数的组件.这是不寻常的,因为jest.mock函数希望将函数用作第二个参数.该字符串可能适合您的测试(取决于其呈现方式),但是在

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>);

这篇关于您如何使用带有道具的Jest模拟React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆