Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test a callback Function using jest and enzyme in ReactJS?

I am new to TDD and I want to test my callback function in my Age component : my Age.js file is following :

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

where my TextFieldComponent is following :

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

I want to test ageValueCallBack function of Age component but I'm not getting any particular method to reach there.

Any insight will be helpful.

Thanks..

like image 269
Ajay Kumar Avatar asked Mar 16 '26 16:03

Ajay Kumar


1 Answers

With enzyme you can trigger the onChange event on the TextFieldComponent using simulate('change', {}, 'someString'). The selectAgeAction in your Age.js needs to be a spy created with jest.fn():

const selectAgeAction = jest.fn()
const component = shallow(<Age selectAgeAction={selectAgeAction} />)
component.find('TextField').simulate('change', {}, '10')
expect(selectAgeAction).toHaveBeenCalledWith('10')
like image 65
Andreas Köberle Avatar answered Mar 18 '26 07:03

Andreas Köberle