2017-11-06 5 views
1

反応成分を反応成分に結合させて反応を試験することはできないようです。誰でも知っている理由は?この点を説明するために、私は、反応がなく通過し、接続するとすぐに失敗する反応コンポーネントのテストをしています。ここで反応が反応した反応成分から反応して反応する成分を反応ユニットテスト

// MyComponent.jsx 
import React from 'react' 

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

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

    render() { 
    return <div></div> 
    } 
} 

export default MyComponent 

は合格テストです:

// MyComponent.test.js 
import React from 'react' 
import MyComponent from '../src/components/MyComponent' 
import { mount } from 'enzyme' 

describe('MyComponent',() => { 
    describe('interactions',() => { 
    let wrapper 
    beforeEach(() => { 
     wrapper = shallow(<MyComponent />) 
    }) 

    it('foo to equal bar',() => { 
     expect(wrapper.state().foo).toEqual('bar') 
    }) 
    }) 
}) 

は今、私はReduxのを導入し、コンポーネントを接続しています:

// MyComponent.test.js 
import React from 'react' 
import MyComponent from '../src/components/MyComponent' 
import { mount } from 'enzyme' 

import configureStore from 'redux-mock-store' 

describe('MyComponent',() => { 
    const state = {} 
    const mockStore = configureStore() 

    describe('interactions',() => { 
    let wrapper 
    beforeEach(() => { 
     wrapper = mount(<MyComponent store={ mockStore(state) } />) 
    }) 

    it('foo to equal bar',() => { 
     expect(wrapper.state().foo).toEqual('bar') 
    }) 
    }) 
}) 

// MyComponent.jsx 

... 

export default connect(function (state){ 
    return { 
    currentUser: state.currentUser 
    } 
})(MyComponent); 

そしてここでは、更新されたテストです

答えて

0

これは、connect()は、店舗相互作用プロセスを管理するラッパーコンポーネントを生成します。 2つ目のスニペットでは、<MyComponent>が元のコンポーネントではなくconnect()で生成されたコンポーネントになりました。実際のコンポーネントの状態の内容を確認するには、レンダリング階層内で深く入れ子になった別のレベルを掘る必要があります。

1

connect()(デフォルトエクスポート)と実際のコンポーネント自体の両方をエクスポートすることをお勧めします。

このようにして、コンポーネントを接続されたバージョンのコンポーネントの外部で個別にテストすることができます。

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

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

    render() { 
    return <div></div> 
    } 
} 

export MyComponent 

export default connect(function (state){ 
    return { 
    currentUser: state.currentUser 
    } 
})(MyComponent); 

し、テスト:

import { MyComponent } from '../src/components/MyComponent' 
import { mount } from 'enzyme' 

describe('MyComponent',() => { 
    describe('interactions',() => { 
    let wrapper 
    beforeEach(() => { 
     wrapper = shallow(<MyComponent />) 
    }) 

    it('foo to equal bar',() => { 
     expect(wrapper.state().foo).toEqual('bar') 
    }) 
    }) 
}) 
+1

良いソリューション - 私はちょうど私があなたに、フロントクラスMyComponentの権利の輸出を追加する必要があると思う明確にするために追加のでしょうか? –

+0

@SpencerBigumこれで、コンポーネントの直後と 'connect()'の前に別々の行にコンポーネントをエクスポートしていることに気づくでしょう。どちらも動作します。 –

+1

オハイオ州よい呼出し - 私はそれを見なかった! –

関連する問題