根据酶docs:
mount(<Component />)
完整 DOM 渲染非常适合您拥有可能与 DOM api 交互的组件,或者可能需要完整生命周期才能完全测试组件(即,componentDidMount 等)的用例。
vs.
shallow(<Component />)
浅层渲染有助于限制您将组件作为一个单元进行测试,并确保您的测试不会间接断言子组件的行为。
vs.
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));
});
请注意渲染, 设置道具 and 寻找选择器乃至综合事件都是浅渲染支持的,所以大多数时候你可以直接使用它。
但是,您将无法获得组件的完整生命周期,因此如果您希望在 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();
});
以上不会通过浅层渲染 or render
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);
});