反应:onChange不是一个函数 [英] React: onChange is not a function

查看:74
本文介绍了反应:onChange不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是刚开始使用React的人,并且正在尝试使用Jest对React应用程序进行单元测试

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

使用Flux模式的应用程序,我已经编写了一个组件"WEATHER",在继续学习另一个组件之前,我想为该组件编写测试并采用TDD方法.

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

天气组件代码:

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

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

,并显示错误消息:天气中找不到'_onChange'属性.

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

推荐答案

TypeError:tree.props.onChange不是函数

TypeError: tree.props.onChange is not a function

您是否尝试过使用以下方式更新测试:

Have you tried updating your test with:

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

请注意破折号.

这篇关于反应:onChange不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆