2016-10-18 5 views
2

{mount}メソッドを使用して私のReactクラスコンポーネントを単体テストしようとしています。クラス変数にアクセスしようとすると(このキーワードを使用して)、テストを実行すると定義されていないエラーが発生します。その後、コンポーネントの状態としてmount(<GridComponent recordArr=[1,2,3] />酵素テストの問題が返されない

 

    export class GridComponent extends React.Component { 
     constructor(props) { 
     super(props) 

     this.state = { 
      pageRecords: [], 
      totalSize: 0 
     } 
     this.options = { 
      page: 1, 
      sizePerPage: 10 
     } 
     this.DataSource = [] //All records will be stored here 
     } 

     componentDidMount() { 
     this.DataSource = this.props.recordArr 
     this.parseProps() 
     } 

     componentWillReceiveProps(nextProps) { 
     this.DataSource = nextProps.recordArr 
     this.parseProps() 
     } 

     parseProps =() => { 
     let pageRecords = [] 
     if (!_.isEmpty(this.DataSource)) { //this.DataSource ==> undefined 
      let startIndex = (this.options.page - 1) * this.options.sizePerPage 
      let count = (this.options.page - 1) * this.options.sizePerPage + this.options.sizePerPage 
      pageRecords = _.slice(this.DataSource, startIndex, count) 
     } 
     this.setState({ 
      ...this.state, 
      pageRecords: pageRecords, 
      totalSize: this.DataSource.length 
     }) 
     } 

     render() { 
     ... //Render the records from this.state.pageRecords 
     } 
    } 

+0

では、矢印関数式を使っている理由はありますか?たぶん、 'this'はあなたの匿名の矢印関数式の中に入っているかもしれません。デバッガを使って 'this'を調べます。 DataSourceプライベート変数ではなく、recordArr propを直接参照してみてください。 – Jecoms

答えて

0

変更this.DataSourceを呼び出し、後this.DataSourceはundefinedに評価ところ、以下の実施例は、テストケースには、Enzyme util setState function:を使用しています。

wrapper.setState({ DataSource: 'somesource' }); 

たとえば、コンポーネントのcomponentWillReceivePropsメソッドは次のようになります。

componentWillReceiveProps(nextProps) { 
    this.setState({ 
    DataSource: nextProps.recordArr, 
    }); 
    this.parseProps() 
} 
+0

DataSourceを状態の内部に格納することができます。しかし、これはReactの反パターンと見なされます。これは、レンダリングメソッドの一部である必要がある状態データを格納することが推奨されているか、または変更されたときにコンポーネントを再度レンダリングすることです(http://stackoverflow.com参照)。/questions/25207703/instance-v-state-variables-in-react-js)を参照してください。 – alonfai

+0

また、this.DataSourceはコンポーネントをレンダリングするときに使用するpageRecordsを計算するためのヘルパーオブジェクトです(この場合、私は反応ブートストラップテーブルグリッドライブラリを使用しています)。したがって、この内部状態を持つことは可能ですが、可能であれば避けることを好む – alonfai

+0

この場合、DataSourceからpageRecordsを計算して、それをあなたの状態に設定するのはなぜですか? pageRecordsの変更が実際にあなたが望むものであるときに再レンダリングコンポーネントとして(あなたはコンストラクタでそれをやろうとすることもできます) – Shota

関連する問題