2016-07-11 10 views
0

Reactコンポーネントのチェックボックスのステータスがcheckedであることを確認しようとしています。これは私のコンポーネントです:React Jest:チェックボックスの状態を取得する方法

class Checkboxes extends React.Component { 
    constructor() { 
     super(); 
     console.log('Hello world!'); 
     this.state = { 
      filterEnabled: { 
       'desserts': true, 
       'juices': true, 
       'meats': true, 
       'veggies': true, 
      }, 
      isApplyingFilter: false 
     }; 
    } 

    getInitialState() { 
     return { 
      filterEnabled: { 
       'desserts': true, 
       'juices': true, 
       'meats': true, 
       'veggies': true 
      }, 
      isApplyingFilter: false 
     }; 
    } 

    render() { 
     const { isApplyingFilter } = this.props; 
     return (
      <div> 
       <div className="row"> 
        <div className="col-md-12"> 
         <div className="mt-checkbox-inline"> 
          <label className="mt-checkbox"> 
           <input type="checkbox" name="desserts" value="desserts" 
            checked={this.state.filterEnabled.desserts} 
           /> 
           <span>desserts</span> 
          </label> 
          <label className="mt-checkbox"> 
           <input type="checkbox" name="juices" value="juices" 
            checked={this.state.filterEnabled.juices} 
           /> 
           <span>juices</span> 
          </label> 
          <label className="mt-checkbox"> 
           <input type="checkbox" name="meats" value="meats" 
            checked={this.state.filterEnabled.meats} 
           /> 
           <span>meats</span> 
          </label> 
          <label className="mt-checkbox"> 
           <input type="checkbox" name="veggies" value="veggies" 
            checked={this.state.filterEnabled.veggies} 
           /> 
           <span>veggies</span> 
          </label> 
         </div> 
        </div> 
       </div> 
      </div> 
     ); 
    } 
} 

私は、次のテストシナリオを書いた:

it('Applying "foods" filter will display only selected food items.',() => { 
    // Locate the checkboxes div 
    var checkboxes = TestUtils.scryRenderedDOMComponentsWithTag(DOM, 'input'); 
    // Pick the first checkbox 
    var cb = checkboxes[0].attributes; 
    // prints out "desserts" 
    console.log('name: ', cb['name'].value); 
    // prints out an empty string 
    console.log('checked: ', cb['checked'].value); 
}); 

私はcb['checked']の値を取得しようとすると、それは単に空の文字列''を出力します。私は代わりにtrueを得ることを期待しています。

チェックボックスの状態を取得する正しい方法は何ですか?

答えて

0

チェックをthis.state.filterEnabledに設定したので、状態を確認するだけで十分です。

expect(this.state.filterEnabled.desserts).toBe(true); 
+0

これは私にエラーを出します: 'TypeError:プロパティ 'の' undefinedの状態 'を読み取れません。 'expect(DOM.state.filterEnabled.desserts)'も試しましたが、それもうまくいきませんでした。 –

+0

'console.log(DOM.state)'は何を出力しますか? – TheAmateurProgrammer

+0

私は 'Object {isApplyingFilter:false}'を取得します。奇妙なことに、それは 'state'のアイテムのうちの1つだけを表示します。 –

関連する問題