【发布时间】:2020-02-27 12:35:48
【问题描述】:
我正在尝试测试一个从数组中返回随机选择的 React 组件的函数。 Bellow,我有一个数组,其中填充了不同类型的 React 组件。
collectionOfComponents = [
<Component1 />
<Component2 />
<Component3 />
<Component4 />
<Component2 />
<Component3 />
...
];
然后我有一个函数,它将从数组中选择一个随机组件并返回该组件,如下所示。
export default () => {
const totalNumberOfComponents = collectionOfComponents.length;
const randomComponentIndex = Math.floor(Math.random() * totalNumberOfQuestions);
const randomComponent = collectionOfComponents[randomComponentIndex];
return cloneElement(randomComponent);
};
我正在尝试编写一个单元测试来涵盖此功能,但是,由于随机返回的 React 组件并不像我想象的那么简单。
我试图模拟函数的返回,但这并没有涵盖 jests 覆盖率报告中函数的所有行。以下是我尝试过的。
jest.mock('common/services/functionName', () => "Random Component");
it('should return random React component', () => {
expect(functionName).toEqual('Random Component');
});
【问题讨论】:
-
你在测试什么?为了报道而报道是没有意义的。 ----- 这里你无法控制随机性,所以你不能真正测试它。您可能想要注入随机生成器,因此在运行测试之前对其进行设置。比如,如果
rand()生成1然后返回Component 1等等。----您也可以多次运行该函数并断言您得到不同的结果,但这意味着您更多地测试Math.randoom()而不是比你的代码。 -
好吧,理想情况下,我想测试一下函数是否返回了 React 组件,不管是什么类型。在阅读了 Enzyme API 文档后,我决定使用下面的方法。您的
What are you testing?问题让我想到了我真正想要测试的内容,这为我指明了以下方向。