繁体   English   中英

在 ReactJS 中使用 jest 和酶测试回调函数?

[英]Test a callback Function using jest and enzyme in ReactJS?

我是 TDD 的新手,我想在我的 Age 组件中测试我的回调函数:我的Age.js文件如下:

import React, { Component } from "react";
import { connect } from "react-redux";
import actions from "../../actions";
import TextFieldComponent from "../Module/TextFieldComponent";

export class Age extends Component {

  ageValueCallBack = age => {
    console.log("value is : ", age);
    this.props.selectAgeAction(age)
  };

  render() {
    const props = {
      onChange: this.ageValueCallBack,
      hintText : 'Eg. 25',
      floatingLabelText: "Age(Years)",
      value : (this.props.usersData) ? this.props.usersData.basic.age : null
    };
    return <TextFieldComponent {...props} />;
  }
}

function mapStateToProps({ usersData }) {
  return {
    usersData
  };
}

export default connect(mapStateToProps, {
  selectAgeAction: actions.selectAgeValue
})(Age);

我的TextFieldComponent如下:

import TextField from "material-ui/TextField";

const TextFieldComponent = props => {
  return (
    <TextField
        onChange={(event, string) => {
        props.onChange(string)
      }}
      floatingLabelText={props.floatingLabelText || "floatingLabelText"}
      value={props.value || null}
      hintText={props.hintText || "hintText will be here"}
      autoFocus ={true || props.autoFocus}
    />
  );
};

我想测试 Age 组件的ageValueCallBack函数,但我没有得到任何特定的方法来到达那里。

任何见解都会有所帮助。

谢谢..

使用酶,您可以使用simulate('change', {}, 'someString')TextFieldComponent上触发onChange事件。 selectAgeAction中的Age.js需要是一个用jest.fn()创建的间谍:

const selectAgeAction = jest.fn()
const component = shallow(<Age selectAgeAction={selectAgeAction} />)
component.find('TextField').simulate('change', {}, '10')
expect(selectAgeAction).toHaveBeenCalledWith('10')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM