2017-03-23 3 views
5

酵素を使用してcomponentWillReceivePropsを含むライフサイクル機能をテストします。リバーステストコンポーネント酵素を使用したウェル受信プローブ

私のコンポーネントの前には、materialUi stylesをラップし、reduxに接続する必要があります。 そうでなければ、FlatButtonを含むmaterial-uiコンポーネントを使用しているため、レンダリング機能にバグがあります。

const wrapper = mount(
     <MuiThemeProvider muiTheme={muiTheme}> 
     <Provider store={store}> 
      <MemoryRouter> 
       <MyComponent /> 
      </MemoryRouter> 
     </Provider> 
     </MuiThemeProvider>) 

// absolutely fail 
wrapper.find(MyComponent).setProps({ something }) 
expect(MyComponent.prototype.componentWillReceiveProps.calledOnce).toBe(true) 

酵素は非ルートコンポーネントの適用を許可しないため、問題は私がMyComponentにsetProps()を使用できないことです。 私は、コンポーネントを変更してcomponentWillReceivePropsやその他の必要な部品をテストすることができません。

componentWillReceivePropsをテストできるようにMyComponentの小道具を設定/変更するにはどうすればよいですか?

答えて

6

コンポーネントを単独でテストする方がよいでしょう。問題は、material-uiがReact contextを使ってその小道を通過していることです。あなたのコンポーネントのコンテキストをこのように指定することができます。

import React from 'react'; 
import { mount } from 'enzyme'; 
import getMuiTheme from 'material-ui/styles/getMuiTheme'; 

const wrapper = mount(
    <MyComponent />, 
    { 
    context: { 
     muiTheme: getMuiTheme(), 
    }, 
    childContextTypes: { 
     muiTheme: React.PropTypes.object.isRequired, 
    } 
    } 
); 

あなたはコンポーネントを分離する必要があるもう一つは<Provider>を削除することです。接続されたコンポーネントをテストする代わりに、Reduxに記載されている方法でコンポーネント自体をテストしてください。docs:Testing Connected Components

すぐに - コンポーネントと接続コンポーネントの両方をエクスポートしてから、コンポーネントをテストします。

import { connect } from 'react-redux' 

// Use named export for unconnected component (for tests) 
export class MyComponent extends Component { /* ... */ } 

// Use default export for the connected component (for app) 
export default connect(mapStateToProps)(MyComponent) 

あなたは今、このようなテストファイルで装飾されていないコンポーネントをインポートすることができます:

import { MyComponent } from './MyComponent'; 

を、最終的なテストはこのようになります:

import React from 'react'; 
import { mount } from 'enzyme'; 
import getMuiTheme from 'material-ui/styles/getMuiTheme'; 
import { MyComponent } from './MyComponent'; 

test('test component',() => { 
    const wrapper = mount(
    <MyComponent />, 
    { 
     context: { 
     muiTheme: getMuiTheme(), 
     }, 
     childContextTypes: { 
     muiTheme: React.PropTypes.object.isRequired, 
     } 
    } 
); 

    // Test something 
    const p = wrapper.find(...); 
    expect(...).toEqual(...); 

    // Change props 
    wrapper.setProps({foo: 1}); 

    // test again 
    expect(...).toEqual(...); 
}); 
-1

あなたはMyComponentのをテストする場合は、プロバイダのような

const wrapper = mount(MyComponent); 

他のものは、MyComponentのの一部ではないはずですので、それのためのユニットテストに含めることはできません。

+0

輸出を持つコンポーネントの例もしそうならば、私はmaterial-uiボタンをレンダリングしたので、テスト中にレンダリング機能にバグが表示されます – Oscar

+0

これは単体テストの範囲外であるため、Material-UIボタンをモックする必要があります。 – brickingup

関連する問題