酶模拟不改变文本区域

时间:2019-05-17 00:33:02

标签: javascript jestjs

我正在尝试一个简单的测试,以验证用户是否可以在文本区域上输入文本,但是由于某种原因,模拟方法无效。

CommentBox组件

class CommentBox extends Component {
  state = { comment: "" };
  handleChange = event => {
    this.setState({ comment: event.value });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.setState({ comment: "" });
  };
  render() {
    return (
      <form>
        <h4>
          Add a CommentBox
          <textarea  onChange={this.handleChange} value={this.state.comment} />
          <div>
            <button onSubmit={this.handleSubmit}>Submit Comment</button>
          </div>
        </h4>
      </form>
    );
  }
}

测试 导出默认的CommentBox;

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

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


it('has a text area 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' ,() => {
    const textarea = wrapped.find('textarea');
    textarea.simulate('change', {
      target: {  , 
        value: 'testing' }
    });
    wrapped.update();
    expect(textarea.prop('value')).toEqual('testing');
});

错误:

●有一个文本区域,用户可以在其中输入

expect(received).toEqual(expected) // deep equality

Expected: "testing"
Received: ""

1 个答案:

答案 0 :(得分:2)

问题#1

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

实际值是event.target.value。但是我相信最好在论点上进行破坏性的构想:

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

问题2: 重新渲染后,您必须再次运行.find('textarea')而不是依靠先前的值;您也不需要wrapped.update()

所以

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

工作正常。