根据酶
文档所述:
对于需要与DOM api交互或需要完整生命周期以完全测试组件(即componentDidMount等)的组件,使用完整DOM渲染的
mount(<Component />)
是理想的选择。
相比之下,浅渲染的
shallow(<Component />)
用于将组件作为单元进行测试,并确保测试不会间接断言子组件的行为。
render
用于将React组件呈现为
静态HTML并分析生成的HTML结构。
在浅层渲染中仍然可以看到底层“节点”,因此例如,您可以使用
AVA作为规范运行器来执行以下操作(稍微有些牵强):
let wrapper = shallow(<TagBox />);
const props = {
toggleValue: sinon.spy()
};
test('it should render two top level nodes', t => {
t.is(wrapper.children().length, 2);
});
test('it should safely set all props and still render two nodes', t => {
wrapper.setProps({...props});
t.is(wrapper.children().length, 2);
});
test('it should call toggleValue when an x class is clicked', t => {
wrapper.setProps({...props});
wrapper.find('.x').last().simulate('click');
t.true(props.toggleValue.calledWith(3));
});
注意,
渲染、
设置props、
查找选择器甚至
合成事件都受浅层渲染的支持,因此大多数情况下您只需使用它即可。但是,您将无法获得组件的完整生命周期,因此如果您希望在componentDidMount中发生某些事情,则应使用
mount(<Component />)
;此测试使用
Sinon来监视组件的
componentDidMount
。
test.only('mount calls componentDidMount', t => {
class Test extends Component {
constructor (props) {
super(props);
}
componentDidMount() {
console.log('componentDidMount!');
}
render () {
return (
<div />
);
}
};
const componentDidMount = sinon.spy(Test.prototype, 'componentDidMount');
const wrapper = mount(<Test />);
t.true(componentDidMount.calledOnce);
componentDidMount.restore();
});
上述内容无法通过
浅渲染或
render。使用
render
将仅提供HTML,因此您仍然可以执行以下操作:
test.only('render works', t => {
const rendered = render(<Test />);
const len = rendered.find('div').length;
t.is(len, 1);
});