按照酶學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
什麼是更高性能? 「渲染」還是「淺」? –