【问题标题】:Test a callback Function using jest and enzyme in ReactJS?在 ReactJS 中使用 jest 和酶测试回调函数?
【发布时间】:2018-03-25 04:03:36
【问题描述】:

我是 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 功能,但我没有任何特定的方法可以到达那里。

任何见解都会有所帮助。

谢谢..

【问题讨论】:

  • 你要做的是你需要一个间谍,sinonJs 很适合那个工作。所以在渲染 Age 组件时,prop selectAgeAction="the sinon spy"。您还需要在您的 TextField 上创建一个 onChangeEvent,然后针对 sinon 间谍进行断言。 sinonjs.org/releases/v4.0.1/spies

标签: javascript reactjs tdd jestjs enzyme


【解决方案1】:

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

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

【讨论】:

  • 这真的很有用,simulate() 的第二个参数你设置为{} 是什么?
  • 这将是调用回调的事件参数,通常类似于{target: value: 'someValue'}
猜你喜欢
  • 2021-03-14
  • 2018-09-28
  • 2018-10-24
  • 2019-04-24
  • 1970-01-01
  • 2019-09-21
  • 2021-07-27
  • 2023-03-14
  • 2019-04-24
相关资源
最近更新 更多