React: onChange is not a function

时光毁灭记忆、已成空白 提交于 2021-02-11 15:53:32

问题


Am new to react and am trying to run unit test for a react app using jest,

The app using the Flux pattern and I have already wrote one component "WEATHER" and before move on to another one I wanted to write test for that component and take TDD approach.

My code running fine but the test fail with this error

TypeError: tree.props.onChange is not a function

The weather component code :

// @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>;
    }
}

Where the test code:

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();

});

Note since am using flow static type checker it always high light this line of code this._onChange = this._onChange.bind(this);

with error message saying : property '_onChange' property not found in the weather.


回答1:


TypeError: tree.props.onChange is not a function

Have you tried updating your test with:

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

Note the dash.



来源:https://stackoverflow.com/questions/39588855/react-onchange-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!