use*_*382 5 testing unit-testing reactjs
您将如何测试接受状态挂钩作为属性的 React 组件?
例如
在应用程序中,它ChildComponent的呈现方式如下:
<App>
<OtherComponent />
<div>
<ChildComponent selectedProperty={selectedProperty}
setSelectedProperty={setSelectedProperty} />
</div>
</App>
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我试图这样做:
component = await render(
<ChildComponent selectedProperty={selectedProperty}
setSelectedProperty={setSelectedProperty} />
);
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何传递这两个属性selectedProperty以及setSelectedProperty应用程序中的哪个属性由父组件处理。
谢谢。
作为一个最小的示例,仅满足您指定的要求,这应该有效:
const selectedProperty = 'whatever';
const setSelectedProperty = () => {};
component = await render(
<ChildComponent selectedProperty={selectedProperty}
setSelectedProperty={setSelectedProperty} />
);
Run Code Online (Sandbox Code Playgroud)
如果您需要验证是否ChildComponent实际调用过setSelectedProperty,您可以使用笑话模拟。
const selectedProperty = 'whatever';
const setSelectedProperty = jest.fn();
component = await render(
<ChildComponent selectedProperty={selectedProperty}
setSelectedProperty={setSelectedProperty} />
);
expect(setSelectedProperty).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用整个 Jest 函数模拟(此处记录:https: //jestjs.io/docs/mock-functions)。
- - - 编辑 - - - -
我认为您实际上是在问:“如何更改传递给组件的状态以响应该组件调用set...?”。很好的问题!您可以不(请参阅下面的更多内容)或检查此问题的答案:How to test a prop update on React component
我建议不要这么做的原因是 1. 你的测试增长太多,2. 没有必要。大概您想测试两件事:
setSelectedProperty被调用,并且selectedProperty。没有必要一起测试它们;分别测试它们。如果您的组件拥有如此多的状态,以至于您觉得需要一起测试它们,则可能是您的组件的状态太多。React 应该尽可能“功能化”并且没有副作用。如果您的组件在这方面变得难以管理且难以测试,请不要放弃测试,重新设计组件。