使用Jest模拟带有道具的React组件 [英] Using Jest to mock a React component with props
问题描述
我有一个React组件,其中包含一些其他组件,这些组件依赖于对Redux存储等的访问,这在进行完整的酶安装时会引起问题.假设这样的结构:
I have a React component which contains some other components that depend on access to a Redux store etc., which cause issues when doing a full Enzyme mount. Let's say a structure like this:
import ComponentToMock from './ComponentToMock';
<ComponentToTest>
...some stuff
<ComponentToMock testProp="This throws a warning" />
</ComponentToTest>
我想使用Jest的.mock()
方法来模拟子组件,因此它不是测试的关注点.
I want to use Jest's .mock()
method to mock out the sub-component, so that it is not a concern for the test.
我知道我可以用类似的东西来模拟一个直线组件:
I'm aware that I can mock out a straight component with something like:
jest.mock('./ComponentToMock', () => 'ComponentToMock');
但是,由于该组件通常会接收道具,因此React会感到不安,并发出有关将未知道具(在本例中为testProp
)传递给<ComponentToMock />
的警告.
However, as this component would normally receive props, React gets upset, giving a warning about unknown props (in this case, testProp
) being passed to <ComponentToMock />
.
我尝试返回一个函数,但是由于悬挂了Jest模拟,您无法返回JSX(据我所知).在这种情况下会引发错误.
I've tried to return a function instead, however you can't return JSX (from what I could tell) in a Jest mock, due to it being hoisted. It throws an error in this case.
所以我的问题是我怎么能
So my question is how can I either
a)获取ComponentToMock
忽略传递给它的道具,或者
a) get ComponentToMock
to ignore props passed to it, or
b)返回一个React组件,该组件可用于模拟我不担心测试的子组件.
b) return a React component that can be used to mock the child component that I'm not worried about testing.
或者...有更好的方法吗?
Or... is there a better way?
推荐答案
There's a note at the bottom of the docs for jest.mock()
for preventing the hoisting behavior:
注意:使用
babel-jest
时,对mock
的呼叫将自动被 悬挂在代码块的顶部.如果要使用doMock
明确避免这种行为.
Note: When using
babel-jest
, calls tomock
will automatically be hoisted to the top of the code block. UsedoMock
if you want to explicitly avoid this behavior.
然后您可以按照描述的方式进行操作:返回一个函数,该函数是不需要测试的组件的存根.
Then you can do as you described: return a function that is a stub of the component you don't need to test.
jest.doMock('./ComponentToMock', () => {
const ComponentToMock = () => <div />;
return ComponentToMock;
});
const ComponentToTest = require('./ComponentToTest').default;
命名存根组件很有用,因为它会在快照中呈现.
It's helpful to name the stub component since it gets rendered in snapshots.
这篇关于使用Jest模拟带有道具的React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!