2016-08-02 83 views
48

在發佈這個問題之前,我試圖在sqa stackexchange中搜索,但是我沒有發現關於淺度和渲染的帖子,所以我希望有人能幫助我。什麼時候應該在酶/反應測試中使用渲染和淺層?

什麼時候應該使用淺層渲染測試反應組件? 基礎上製作的Airbnb文檔,我做了一些意見上的兩個的區別:

  1. 由於淺正在測試組件爲單位,所以它應該用於「父」組件。 (例如表格,包裝等)

  2. 渲染是針對子組件的。

我問這個問題的原因是,我有一個很難弄清楚,我應該使用哪一個(雖然文檔說,他們是非常相似)

那麼,如何我知道在特定場景中使用哪一個?

回答

83

按照酶學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); 
}); 

希望這有助於!

+1

明確的解釋人! –

+1

我還沒有得到100%,爲什麼三個動詞帶來不同的方法。例如,可以在淺層使用wrapper.getNode(),但不能在渲染中使用。任何解釋/鏈接/文檔/博客,可以幫助我解決這個問題? – Paulquappe

+0

什麼是更高性能? 「渲染」還是「淺」? –

相關問題