如何在使用Enzyme和Jest的单元测试中检查嵌套的React组件的值
我是测试的新手,我想访问const
I'm new in testing and I would like to access to a const
const Label = ({ intl, data }) => {
if (data && data.length === 0) {
return <div>{intl.translate('no_data')}</div>
}
return null
}
测试文件:
test('should return null when is data', () => {
const component = shallow(<StatisticsGraph {...mockPropsForComponent} />)
const label = component.find(Label)
expect(label).toEqual(null)
})
变量mockPropsForComponent
具有带有某些值的变量data
.
我想知道测试通过的Label
的值
The variable mockPropsForComponent
has the variable data
with some values.
I want to know the value of Label
for the test pass
有不同的解决方案,可以解决不同的问题.
There are different solutions, for different problems to solve.
将Label
组件隔离在其自己的文件中并导出.
Isolate the Label
component in its own file and export it.
const Label = ({ intl, data }) => {
if (data && data.length === 0) {
return <div>{intl.translate('no_data')}</div>
}
return null
};
export default Label;
然后,分别进行测试.就像 Quentin提到的,组件只是可以调用的函数.
Then, test it individually. Like Quentin mentioned, a component is just a function you can call.
import Label from './Label';
test('should return null when there is data', () => {
expect(Label({ data: ['anything'] })).toEqual(null);
})
测试组件的组成
由于您正在测试StatisticsGraph
,并且您的Label
组件没有可识别的选择器,因此您可以
Testing a composition of components
Since you're testing StatisticsGraph
and that your Label
component has no identifiable selector, you could use snapshots to make sure it's rendered correctly.
import React from 'react';
import { render } from 'enzyme';
import toJson from 'enzyme-to-json';
test('should return null when is data', () => {
const wrapper = render(<StatisticsGraph {...mockPropsForComponent} />);
expect(toJson(wrapper)).toMatchSnapshot();
});
手动测试组件
如果您真的要手动测试每个组件的零件,则可能需要更改Label
以便于查找.
const Label = ({ intl, data }) => (
<div className="label">
{Boolean(data && data.length === 0) && intl.translate('no_data')}
</div>
);
然后,应该找到该组件,并且可以使用 .isEmpty()
检查它是否有效.
Then, the component should be found and you could use .isEmpty()
to check that it worked.
test('should return null when is data', () => {
const component = shallow(<StatisticsGraph {...mockPropsForComponent} />);
const label = component.find(Label);
expect(label.isEmpty()).toBe(true);
});