根据酶文档:
mount(<Component />)
对于完整的 DOM 渲染,非常适用于您的组件可能与 DOM apis 交互的用例,或者可能需要完整的生命周期以完全测试组件(即 componentDidMount 等)
对比
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
只会为您提供 html,因此您仍然可以执行以下操作:
test.only('render works', t => {
// insert Test component here...
const rendered = render(<Test />);
const len = rendered.find('div').length;
t.is(len, 1);
});
希望这可以帮助!