首页 > 解决方案 > 使用 Enzyme.js 模拟输入更改时出现错误 - 状态不正确更新

问题描述

我正在尝试测试表单中的输入字段。但是,当Enzyme.js用于simulate更改输入字段时,state会错误地更新,因为日志显示该simulate函数已在名为undefined.I 的状态下创建了新记录。我非常乐意提供帮助。

问候

初始组件状态如下所示:

this.state = {
    submission: {
        firstName: '',
        lastName: '',
        email: '',
        date: new Date(),
        validation: {
            email : {isInvalid: false, message: ""},
            firstName : {isInvalid: false, message: ""},
            isValid : true,
            lastName : {isInvalid: false, message: ""}
        }
    }
}

这是测试功能:

it('should respond to change event and change the state of the Component', () =>{
    const wrapper = shallow(<ApplicationForm/>);
    console.log(wrapper.find('#firstName').debug());

    wrapper.find('#firstName').simulate(
        'change', {
            target: {
                name: 'firstName',
                value: 'John'
            }
        }
    )

    expect(wrapper.state().submission.firstName).to.equal('John');
})

这是我期望的状态:

submission: {
    firstName: 'John',
    ...
}

这就是我检查结果时得到的结果debug

submission: {
    firstName: '',
    lastName: '',
    email: '',
    date: new Date(),
    validation: {
        email : {isInvalid: false, message: ""},
        firstName : {isInvalid: false, message: ""},
        isValid : true,
        lastName : {isInvalid: false, message: ""}
    },
    undefined: 'John'
}

下面你可以看到渲染表单的代码:

<input type="text"
    id="firstName"
    className="form-control form-control-sm"
    placeholder="First name"
    onChange={this.updateSubmission.bind(this)}
/>

updateSubmission 函数如下所示:

updateSubmission(event) {
    let updatedSubmission = Object.assign({}, this.state.submission);

    updatedSubmission[event.target.id] = event.target.value;
    this.setState({
        submission: updatedSubmission
    });
}

标签: reactjstestingenzyme

解决方案


updateSubmission处理程序使用target.id

updatedSubmission[event.target.id] = event.target.value;

但在您使用的测试中name

        target: {
            name: 'firstName',
            value: 'John'
        }

修复要使用的测试target对象id: 'firstName'应该修复它。(或者您可以切换到name在您的代码中使用。)


推荐阅读