2016-11-29 66 views
1

我有一個React組件,我正在試圖使用Enzyme/Jest進行測試。我想弄清楚什麼是最合適的測試,以確保組件已經呈現。測試React組件是否已呈現

我的組件有一個道具shouldRender,如果爲false,將導致組件不呈現。我的組件看起來是這樣的:

import React from 'react'; 

const propTypes = { 
    shouldRender: React.PropTypes.bool, 
}; 

class MyComponent extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     foo: 'bar', 
    }; 
    } 

    render() { 
    if (!this.props.shouldRender) { 
     return null; 
    } 

    return (
     <div> 
     <span>My component</span> 
     </div> 
    ); 
    } 
} 

MyComponent.propTypes = propTypes; 

export default MyComponent; 

我有一個測試,看起來像這樣:

import React from 'react'; 
import { shallow } from 'enzyme'; 
import MyComponent from '../MyComponent'; 

describe('MyComponent',() => { 
    it('Should render if we want it to',() => { 
    const component = shallow(<MyComponent shouldRender />); 

    expect(component).toBeDefined(); // Passes 
    }); 

    it('Should not render if we do not want it to',() => { 
    const component = shallow(<MyComponent />); 

    expect(component).not.toBeDefined(); // Does not pass, as component isn't undefined. 
    }); 
}); 

我想第二次測試失敗,因爲該組件沒有渲染。有沒有更好的方法來測試組件是否已經呈現?

如果需要,歡迎提供更多信息。

謝謝!

+0

只是一個通知。根據docs返回未定義'render'不是一個有效的選項。 「你也可以返回'null'或'false'來表示你不想渲染任何東西。」 –

+0

Woops - 我只是在現場爲手冊寫了一個更簡化的版本 - 我將修復代碼現在。謝謝! –

+1

順便說一下'isEmpty'方法。 https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/isEmpty.md –

回答

1

所以我和一些人聊了一會兒,並決定說我可能會以這種錯誤的方式進行討論。

這可能是一個更好的主意,以確定這是否由父組件呈現,否則任何時候我想使用MyComponent,我將不得不通過這個shouldRender道具進入它。

MyComponent現在看起來是這樣的:

import React from 'react'; 

class MyComponent extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     foo: 'bar', 
    }; 
    } 

    render() { 
    return (
     <div> 
     <span>My component</span> 
     </div> 
    ); 
    } 
} 

MyComponent.propTypes = propTypes; 

export default MyComponent; 

MyParentComponent使用MyComponent看起來是這樣的:

import React from 'react'; 

const propTypes = { 
    myComponent: React.PropTypes.bool, 
}; 

class MyParentComponent extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     boz: 'baz', 
    }; 
    } 

    render() { 
    return (
     <div> 
     { this.props.myComponent && 
      <MyComponent /> 
     } 
     </div> 
    ); 
    } 
} 

export default MyComponent; 

不僅讓MyComponent更可重複使用的,它消除了對測試的需求我想完全寫。感謝大家看到這個。

0

我認爲Jest的快照測試是你需要的。通過在測試失敗時進行快照測試,您可以檢查是否有意或無意改變。看看他們的例子here

+0

這就是我的想法,但後來我意識到我不應該快照測試 - 這更有意義有條件地在使用它的父/基組件中渲染組件。這樣子組件實際上是可重用的:) –

相關問題