2

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..

1
  • What you have to do is that you need a spy, sinonJs is good for that job. So when you render Age component, prop selectAgeAction="the sinon spy". Also you need to make an onChangeEvent on your TextField, and then assert against the sinon spy. sinonjs.org/releases/v4.0.1/spies Commented Oct 13, 2017 at 5:14

1 Answer 1

9

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')
Sign up to request clarification or add additional context in comments.

2 Comments

This is really useful, what is the second argument of simulate() which you set to {}?
This would be the event argument the callback is called with, usually something like {target: value: 'someValue'}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.