如何使用 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

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


绝地无双
浏览 142回答 3
3回答

尚方宝剑之说

当您的组件设置状态的电子邮件属性时。您可以检查组件的状态,例如:expect(component.state().email).toEqual('abc@hello');

有只小跳蛙

尝试这个方法,成分import React, { Component } from "react";export class YourComponent extends Component {&nbsp; state = {email: ''};&nbsp; handleInputChange = (event) => {&nbsp; &nbsp; this.setState({ email: event.target.value });&nbsp; };&nbsp; &nbsp;&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; id='email'&nbsp; &nbsp; &nbsp; &nbsp; onBlur={this.handleInputChange}&nbsp; &nbsp; &nbsp; &nbsp; name='email'&nbsp; &nbsp; &nbsp; &nbsp; type='text'&nbsp; &nbsp; &nbsp; &nbsp; value={this.state.email}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; );&nbsp; }}&nbsp;export default YourComponent;测试文件&nbsp; &nbsp; describe("Blur test", () => {&nbsp; &nbsp; &nbsp; it("input component", () => {&nbsp; &nbsp; &nbsp; &nbsp; const component = mount(<YourComponent />);&nbsp; &nbsp; &nbsp; &nbsp; let inputs = component.find('input');&nbsp; &nbsp; &nbsp; &nbsp; const inputValue =&nbsp; 'abc@hello';&nbsp; &nbsp; &nbsp; &nbsp; inputs.at(0).simulate('blur', { target: { value: inputValue } });&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; inputs = component.find('input');&nbsp; &nbsp; &nbsp; &nbsp; console.log(inputs.debug());// you will get updated value here&nbsp; &nbsp; &nbsp; &nbsp; expect(inputs.props().value).toEqual(inputValue);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });

HUX布斯

您在测试中引用了props().value,而输入元素没有这样的属性。所以你需要value在输入中添加 prop<input&nbsp; id='email'&nbsp; onBlur={this.handleInputChange}&nbsp; name='email'&nbsp; type='text'&nbsp; value={this.state.email}/>为了测试预期的 props 值,您需要强制重新渲染组件以反映新值。在 中Enzyme,我们可以通过使用 来做到这一点wrapper.setProps({})。您可以传递所需的值wrapper.setProps({value: 'abc@hello'})或只是一个空对象,此处的目的是导致重新渲染。const inputs = component.find('input');expect(inputs.length).toEqual(2);&nbsp; // test case passesinputs.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');&nbsp; // test should pass&nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript