根据酶docs:
mount(<Component />) 用于完整 DOM 渲染非常适合您拥有可能与 DOM api 交互的组件或可能需要完整生命周期才能完全测试组件(即 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));
});
注意 rendering、setting props 和 finding selectors 甚至 synthetic events 都支持浅渲染,所以大多数时候你可以使用它。
但是,您将无法获得组件的完整生命周期,因此如果您希望在 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);
});
希望这会有所帮助!