2017-06-27 7 views
0

私はちょうどjestと酵素を使い始めました。redux-mock-storeによるユニットテスト - このユニットテストをパスするにはどうしたらいいですか?

ユニットテストの作業に問題があります。 私はredux-mock-storeを使ってストアオブジェクトをモックします。

it('shows an li for each comment',() => { 
    expect(container.find('li').length).toBe(2); 
}); 

私は2つの要素を期待していますが、0の要素があります。

私は長い間このエラーに悩まされています。

誰でもこのテストに合格する方法を理解してもらえますか?冗談のテストランナーから

テスト結果

Error: expect(received).toBe(expected) 

Expected value to be (using ===): 
    2 
Received: 
    0 
Expected :2 
Actual :0 

CommentList.test.jsあなたがいずれかのエクスポートにCommentListコンポーネントとテストを飾ったことはできません

import React, { Component } from 'react'; 
import { shallow, mount, render } from 'enzyme'; 
import configureStore from 'redux-mock-store'; 

import CommentList from '../../components/CommentList'; 
jest.unmock('../../components/CommentList'); 

describe('CommentList',() => { 

    const initialState = {comments: ['New Comment', 'Other New Comment']}; 
    const mockStore = configureStore(); 

    let store; 
    let container; 

    beforeEach(() => { 
     store = mockStore(initialState); 
     container = shallow(<CommentList store={store} />); 
    }); 

    //This passes. 
    it('renders the connected component',() => { 
     expect(container.length).toBe(1); 
    }); 

    //This fails. 
    it('shows an li for each comment',() => { 
     expect(container.find('li').length).toBe(2); 
    }); 

}); 

CommentList.js

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 

const propTypes = {}; 
const defaultProps = {}; 

const CommentList = (props) => { 

    const list = props.comments.map((comment) => { 

     <li key={comment}>{comment}</li> 
    }); 

    return (
     <ul className="comment-list"> 
      {list} 
     </ul> 
    ) 

}; 

function mapStateToProps(state) { 
    return { 
     comments: state.comments 
    } 
} 

CommentList.propTypes = propTypes; 
CommentList.defaultProps = defaultProps; 

export default connect(mapStateToProps)(CommentList); 

答えて

1

私があなたならば、それはそのように動作するはずだと思いますbeforeEach()の中にshallowの代わりにmountを使用してコンポーネントをレンダリングします。

浅い木が(CommentList)を接続しますのでレンダラーは、あなたのliコンポーネントを表示ほど深くつもりはないレンダリングで - > CommentList - > UL - あなたはまた行くためにdiveを使用することができます>李

あなたが浅い状態にしたい場合に備えて、必要に応じて一層深く。ドキュメント内のを参照してください: http://airbnb.io/enzyme/docs/api/ShallowWrapper/dive.html

+0

ありがとう!!わかった! – hytm

1

コメントの小道具を渡すだけで、またはCommentListコンポーネントをプロバイダにラップすることができますそれに店を渡す。あなたがここに見つけることができます

<Provider store={store}> 
    <CommentList /> 
</Provider> 

詳細情報: http://redux.js.org/docs/recipes/WritingTests.html#connected-components

あなたの例を作るためにあなたがリストを変更する必要が動作します。

const list = props.comments.map(comment => (
    <li key={comment}>{comment}</li> 
)); 
+0

私は両方の方法を試しましたが、私はまだ私のテストで同じエラーがあります。私は何か完全に間違っているのですか? – hytm

+0

このテストコードを書き込む前に、この記事(https://medium.com/@gethylgeorge/testing-a-react-redux-app-using-jest-and-enzyme-b349324803a9)を読んだことがあります。 – hytm

+0

@Hayatomoそれは動作していない理由は、あなたがコメントを表現する方法に問題があるということです。 'map'関数はあなたのコードに値を返さなければ何もしません。 – lucas

関連する問題