use*_*695 6 javascript unit-testing reactjs jestjs enzyme
我正在使用Jest和Enzyme对该简单组件进行单元测试render():
render() {
return (<Input
id='foo'
ref={input => { this.refInput = input }}
/>)
}
it('should render Input', () => {
wrapper = shallow(<Component />)
expect(wrapper.find(Input)).toHaveLength(1)
})
Run Code Online (Sandbox Code Playgroud)
我还使用了Jest的coverage选项,在那里我看到
ref={input => { this.refInput = input }}
Run Code Online (Sandbox Code Playgroud)
我的考试不包括在内。我需要怎么做才能获得此样本组件的完整单元测试?
ref附加到组件的实例,因此您将不得不使用它mount来获取组件的实例。
要测试ref,请添加以下行
expect(wrapper.instance().refInput).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)
最后结果:
render() {
return (<Input
id='foo'
ref={input => { this.refInput = input }}
/>)
}
it('should render Input', () => {
const wrapper = mount(<Component />);
expect(wrapper.find(Input)).toHaveLength(1)
expect(wrapper.instance().refInput).toBeTruthy();
})
Run Code Online (Sandbox Code Playgroud)
小智 7
我这样解决了这个问题:
const ref = React.createRef();
const props = { register: jest.fn(params => ref), label: "label text", ...params };
let wrapper = mount(
<ThemeProvider theme={theme}>
<Input {...props} />
</ThemeProvider>
);
expect(wrapper.find(Entity).getElement().ref).toBe(ref);
Run Code Online (Sandbox Code Playgroud)
我在输入内部有实体组件,它接收 ref 函数。
| 归档时间: |
|
| 查看次数: |
7797 次 |
| 最近记录: |