使用 Jest 模拟带有 props 的 React 组件 [英] Using Jest to mock a React component with props
问题描述
我有一个 React 组件,其中包含一些其他组件,这些组件依赖于对 Redux 存储等的访问,这在执行完整的 Enzyme 装载时会导致问题.让我们说一个这样的结构:
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');
然而,由于这个组件通常会接收 props,React 会感到不安,发出关于未知 props(在这种情况下,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
忽略传递给它的 props,或者
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?
推荐答案
文档用于 jest.mock()
以防止提升行为:
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 模拟带有 props 的 React 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!