4m1*_*m1r 148
根据Enzyme docs:
mount(<Component />) 对于完全DOM渲染非常适合您拥有可能与DOM apis交互的组件的情况,或者可能需要整个生命周期才能完全测试组件(即componentDidMount等)
与
shallow(<Component />) 对于浅层渲染,可以限制自己将组件作为一个单元进行测试,并确保测试不会间接断言子组件的行为.
与
render用于将反应组件呈现给静态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));
});
Run Code Online (Sandbox Code Playgroud)
请注意,浅渲染支持渲染,设置道具和查找选择器甚至合成事件,因此大多数情况下您可以使用它.
但是,您将无法获得组件的整个生命周期,因此如果您希望在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();
});
Run Code Online (Sandbox Code Playgroud)
以上不会通过浅渲染或渲染
render 将仅为您提供HTML,因此您仍然可以执行以下操作:
test.only('render works', t => {
// insert Test component here...
const rendered = render(<Test />);
const len = rendered.find('div').length;
t.is(len, 1);
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
shallow()和mount()之间的区别在于,shallow()将组件与它们呈现的子组件隔离开来测试组件,而mount()进行得更深并测试组件的子组件。对于shallow(),这意味着如果父组件渲染了另一个无法渲染的组件,则父组件上的shallow()渲染仍将通过。
| 归档时间: |
|
| 查看次数: |
37973 次 |
| 最近记录: |