按照酶学docs:
mount(<Component />)
的全部DOM渲染是理想的,你有可能与DOM API的交互,或者可能需要以完全测试组件的整个生命周期的组件使用情况(即,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));
});
注意渲染,设置道具和找到选择器甚至合成事件都支持浅渲染,所以大多数时候你可以使用它。
但是,您将无法获得组件的完整生命周期,因此如果您期望发生在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);
});
希望这有助于!
明确的解释人! –
我还没有得到100%,为什么三个动词带来不同的方法。例如,可以在浅层使用wrapper.getNode(),但不能在渲染中使用。任何解释/链接/文档/博客,可以帮助我解决这个问题? – Paulquappe
什么是更高性能? “渲染”还是“浅”? –