首页 > 解决方案 > 如何触发模糊事件以使用 Enzyme 更改输入元素的值?

问题描述

我想为输入表单编写测试,但无法触发 Blur 事件。

我有一个包含以下输入元素的反应组件:

<input
  id='email'
  onBlur={this.handleInputChange}
  name='email'
  type='text'
/>

我还email定义了状态和设置状态的函数:

  handleInputChange = (event) => {
    this.setState({ email: event.target.value });
  };

我的测试文件中有以下内容:

    const inputs = component.find('input');

    expect(inputs.length).toEqual(2);                             // test case passes
    inputs.at(0).simulate('blur', { target: { value: 'abc@hello' } });
    expect(inputs.at(0).props().value).toEqual('abc@hello');      //test fails

如果我尝试模拟更改事件,测试也会失败: inputs.at(0).simulate('change', { target: { value: 23 } });

在这两种情况下,我都会收到错误:

    Expected: "abc@hello"
    Received: undefined

看来我的代码没有触发该事件。谁能告诉我我做错了什么

标签: javascriptreactjstypescriptjestjsenzyme

解决方案


您在测试中引用了props().value并且输入元素没有这样的属性。所以你需要在value输入中添加道具

<input
  id='email'
  onBlur={this.handleInputChange}
  name='email'
  type='text'
  value={this.state.email}
/>

为了测试预期的道具值,您需要强制重新渲染组件以反映新值。在 中Enzyme,我们可以使用wrapper.setProps({}). 您可以传递所需的值wrapper.setProps({value: 'abc@hello'})或只是一个空对象,这里的目的是导致重新渲染。

const inputs = component.find('input');

expect(inputs.length).toEqual(2);  // test case passes
inputs.at(0).simulate('blur', { target: { value: 'abc@hello' } });

// setProps should be called on the shallow or root wrapper.
component.setProps({}); // cause rerender.
expect(inputs.at(0).props().value).toEqual('abc@hello');  // test should pass  

推荐阅读