2016-09-20 150 views
0

是新來的反應,並利用流量格局正在嘗試運行單元測試的用玩笑的反應程序,陣營:的onChange不是一個函數

的應用程序,我已經寫了一個組件「天氣」和前移動到另一個我想寫測試該組件,並採取TDD方法。

我的代碼運行良好,但測試失敗,此錯誤

TypeError: tree.props.onChange is not a function 

天氣組件代碼:

// @flow 

import React from 'react'; 
import api from '../api'; 
import weatherStore from '../stores/weatherStore'; 

//read from weather store 
let _getState =() => { 
    return {weather: weatherStore.returnWeather()}; 
}; 

export default class Weather extends React.Component { 



    constructor(proporties) { 
     super(proporties); 

     this._onChange = this._onChange.bind(this); 

     this.state = _getState(); 

    } 
    componentWillUnmount() { 
     weatherStore.removeListener('change', this._onChange); 
    } 
    componentDidMount() { 
     api.getWeather(); 
     weatherStore.on('change', this._onChange); 
    } 

    _onChange() { 
     this.setState(_getState()); 
    } 

    render() { 
     let weatherState = this.state.weather.map(weather => { 

      return <div key={weather.id} className="pull-right row"> 

         <div> 
          <span>{weather.main.temp} C</span><br /> 
         </div> 
        </div>; 
     }) 

     return <div>{weatherState}</div>; 
    } 
} 

當測試代碼:

import React from 'react'; 
import Weather from '../js/components/Weather'; 
import renderer from 'react-test-renderer'; 

it('should render weather temp and city',()=> { 
    const component = renderer.create(
     <Weather /> 
    ); 

    let tree = component.toJSON(); 
    expect(tree).toMatchSnapshot(); 

    // manually trigger the callback 
    tree.props._onChange(); 
    // re-rendering 
    tree = component.toJSON(); 
    expect(tree).toMatchSnapshot(); 

}); 

注意,因爲我使用流動靜態型檢查器它總是高亮此行代碼this._onChange = this._onChange.bind(this);

帶有錯誤消息說:屬性'_onChange'屬性沒有在天氣中找到。

+0

當console.log(tree)''時,你會得到什麼? –

回答

1

TypeError: tree.props.onChange is not a function

你有沒有試着用更新的測試:

// manually trigger the callback 
tree.props._onChange(); 

注意儀表。

+0

是的,我已更新測試相同的錯誤。我已經更新了答案 – user3462064

+1

能否請您發佈的 '的console.log結果(JSON.stringify(tree.props,空,2));' 請把下面的期望(樹)線 –

+0

輸出這一權利是空對象{} – user3462064

相關問題