Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React jest test stops working when using [event.target.name]

Having the following comp

constructor(props) {
        super(props);
        this.state = {
            comment: ''
        }
    }

    handleChange = event => {
            this.setState({ [event.target.name]: event.target.value })
        }
    
    render() {
            return (
                <form onSubmit={this.handleSubmit}>
                    <h4>Add a Comment</h4>
                    <textarea name="comment" onChange={this.handleChange} value={this.state.comment} />
                    <div>
                        <button>Submit Comment</button>
                    </div>
                </form>
            )
        }

wont let me pass the test when writting the following

it('has a text area where the users can type in', () => {
    wrapped.find('textarea').simulate('change', {
        target: {value: 'new comment'}
    })
    wrapped.update()
    expect(wrapped.find('textarea').prop('value')).toEqual('new comment')

})

But the same test passes when using the following handlechange

 handleChange = event => {
        this.setState({ comment: event.target.value })
    }

How can I make this test pass while using [event.target.name]

like image 716
mouchin777 Avatar asked Jan 19 '26 21:01

mouchin777


1 Answers

You need to have name property as well in the event.target object

const event = {target: {name: "somename", value: "somevalue"}};

Try the below,

it("should respond to name change", _ => {
  const event = {target: {name: "somename", value: "somevalue"}};
  const wrapper = mount(
    <Component />
  );
  const handleChangeSpy = jest.spy(wrapper.instance(), "handleChange");
  wrapper.update();
  wrapper.ref('somename').simulate('change', event);
  expect(handleChangeSpy.calledOnce).to.equal(true);
});

Or if Shallow rendered,

 it("should respond to name change", _ => {
      const event = {target: {name: "comment", value: "somevalue"}};
      const wrapper = shallow(<Component />);
      const myTextArea = wrapper.find(#comment);
      myTextArea.simulate('change', event);
      expect(...);
    });
like image 102
deechris27 Avatar answered Jan 22 '26 13:01

deechris27



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!