reactjs - 使用 Enzyme.usestate 错误更新模拟输入更改时的错误

标签 reactjs testing enzyme

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

问候

初始组件状态如下所示:

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
    });
}

最佳答案

updateSubmission 处理程序使用 target.id:

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

但在测试中你使用name:

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

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

关于reactjs - 使用 Enzyme.usestate 错误更新模拟输入更改时的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532449/

相关文章:

reactjs - 如何模拟模块中的特定功能

reactjs - Jest 性能问题

javascript - 使用 onBoundsChanged react 谷歌地图重新渲染问题

javascript - 使用TestUtils模拟ReactJS表单标签不会触发 `onSubmit`

reactjs - 如何使用 React js 处理非常大的文件下载

javascript - 如何将测试用例组织成大型应用程序的测试套件

javascript - 我的 React 选项卡代码运行良好,但我需要更改 html 结构

testing - 为什么 QuickCheck 放弃了?

python - Django 测试运行程序忽略 --settings 选项

javascript - React/JestJS/ enzyme : How to test for ref function?