2017-02-17 153 views
0

我有一個組件,根據傳遞給它的道具呈現不同的子組件。使用jestjs斷言反應組件子(ren)存在/不存在

我正在使用jestjs進行測試,並且我想斷言「父」組件會根據父組件中傳遞的道具呈現適當的子/子組件。

簡化的片段:

父組件

import ComponentA from './componentA' 
import ComponentB from './componentB' 

function ParentComponent(props) { 
    const { step } = props 
    switch(step) { 
    case 'A': 
     return (<ComponentA />) 
    case 'B': 
     return (<ComponentB />) 
    } 
} 

測試

import ParentComponent from './ParentComponent' 
import ComponentA from './ComponentA' 
import ComponentB from './ComponentB' 

const renderCompo = (props = {}) => mount(
    <ParentComponent step={'A'} {...props} /> 
) 

describe('ParentComponent',() => { 

    it('should render the <ComponentA /> as its child when passed `A` as the value of step props',() => { 
    const renderedComponent = renderCompo() 
    // I know this is not correct use of find but this serve as illustration of what I'm trying to assert 
    expected(renderedComponent.find(<ComponentA />).length).toEqual(1) 
    }) 
    it('should NOT render the <ComponentB /> as its child when passed `A` as the value of step props',() => { 
    const renderedComponent = renderCompo() 
    // I know this is not correct use of find but this serve as illustration of what I'm trying to assert 
    expected(renderedComponent.find(<ComponentA />).length).toEqual(0) 
    }) 

    it('should render the <ComponentB /> as its child when passed `B` as the value of step props',() => { 
    const renderedComponent = renderCompo({ step: 'B' }) 
    expected(renderedComponent.find(<ComponentB />).length).toEqual(1) 
    }) 
    it('should render the <ComponentA /> as its child when passed `B` as the value of step props',() => { 
    const renderedComponent = renderCompo({ step: 'B' }) 
    expected(renderedComponent.find(<ComponentB />).length).toEqual(0) 
    }) 
}) 

我嘗試了各種方法來斷言這個,但沒有運氣。

我知道如何使用find方法 - 例如 - 搜索divh3,但我想測試孩子對一個反應組件,而不是孩子渲染,因爲它可能是根DOM節點相同的DOM節點在不同的組件中。

------------------- 編輯: -------------------

使用

expect(renderedComponent.find(ComponentA).length).toEqual(1) 

實際工作完全

我的部件不符合規格。

回答

1

嘗試在每個it中明確安裝帶有所需道具的組件。然後,當您使用Jest時,您可以使用.toMatchSnapshot()方法。然後可以打開生成的快照文件,以確保所有內容都按照您的預期進行渲染。

注意你需要enzyme-to-json爲下面的例子上班

it('should render the <ComponentA /> as its child when passed `A` as the value of step props',() => { 
    const wrapper = mount(<ParentComponent step={'A'} />) 
    expected(toJson(wrapper)).toMatchSnapshot() 
    }); 
it('should render the <ComponentB /> as its child when passed `B` as the value of step props',() => { 
    const wrapper = mount(<ParentComponent step={'B'} />) 
    expected(toJson(wrapper)).toMatchSnapshot() 
    }) 
+0

感謝您的答覆,儘量避免額外的依賴 - 如果未正確地理解,我至少需要作出反應 - 測試 - 渲染 - 我去回到我已經嘗試過的一切。當我發現我的測試正在使用: 'expect(renderedComponent.find(ComponentA).length).toEqual(1)' 問題是我的代碼不符合規範(或我的想法它寫測試)。 –

+0

不想額外依賴的原因是什麼?這隻需要額外的開發依賴關係,所以不會膨脹你的應用程序。很高興你能工作,但我強烈建議研究spanshot測試。這將爲您節省大量時間和未來的麻煩。 – spirift

+0

我同意我認爲它有好處,爲了簡化創建/編輯測試,我打算檢查快照。事情是...這個項目的死路線, –