Miqdad
Miqdad

Reputation: 5

Enzyme: Value props returns undefined in simulating onChange event

I'm trying to simulate onChange event with simulate function. I also have passed the second argument to mock event onChange as the value is part of the event. But somehow it gives me unexpected result as value that I have passed to the second argument returns undefined instead of new comment. Any idea of this issue?

CommentBox.js

import React from 'react';

class CommentBox extends React.Component {
    state = {
        comment: ''
    }

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

    handleSubmit = event => {
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <h4>Add a comment</h4>
                <textarea onChange={this.handleChange} value={this.state.comment} />
                <div>
                    <button>Submit Comment</button>
                </div>
            </form>
        )
    }
}

export default CommentBox;

CommentBox.text.js

import React from 'react';
import { mount } from 'enzyme';
import CommentBox from 'components/CommentBox';

let wrapped;

beforeEach(() => {
    wrapped = mount(<CommentBox />);
})

afterEach(() => {
    wrapped.unmount();
})

it('has a textarea and a button', () => {
    expect(wrapped.find('textarea').length).toEqual(1);
    expect(wrapped.find('button').length).toEqual(1);
});

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

    expect(wrapped.find('textarea').prop('value')).toEqual('new comment');
});

I expect the output of new comment, but the actual is returned undefined

Upvotes: 0

Views: 271

Answers (2)

BeautifulWorld
BeautifulWorld

Reputation: 704

Please try with below along-with function implementation as suggested by Kishan Jaiswal:

class CommentBox extends React.Component {
constructor(props) {
    super(props);
    this.state={
      comment: ''
    }
  }
}

Upvotes: 0

Kishan Jaiswal
Kishan Jaiswal

Reputation: 664

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

first do this changes ,its wrong way to set value in comment variable

Upvotes: 3

Related Questions