【问题标题】:How to input text into form during React/Jest/Enzyme Shallow Rendering testing?如何在 React/Jest/Enzyme 浅渲染测试期间将文本输入表单?
【发布时间】:2017-06-08 04:09:16
【问题描述】:

我有以下表格:

<form onSubmit={ this.handleSubmit } className="form-login">
    <ul>
        <li className="rel">
            <div className="icon-user-circle-o"></div>
            <input type="text" id="input-auth-username" placeholder="username" />
        </li>
        <li className="rel">
            <div className="icon-lock"></div>
            <input type="password" id="input-auth-password" placeholder="password" />
        </li>
        <li>
            <button className="btn-green" type="submit">Login</button>
        </li>
    </ul>
</form>

我目前的测试

第一个测试通过了,这是我目前无法编写的第二个测试。

describe('User Login', () => {
    it('should fail if no credentials are provided', () => {
        const fakeEvent = { preventDefault: () => '' };
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit', fakeEvent);
        expect(loginComponent.find(Notification).length).toBe(1);
        // console.log(loginComponent.debug());
    });

    it('should log user into dashboard if correct credentials are provided', () => {
        const credentials = { username: 'joe', password: 'myspecialpassword' };

    });
});

我想测试表单提交,但是我首先需要在#input-auth-username#input-auth-password 输入字段中输入文本。

您如何使用 Enzyme 做到这一点?

【问题讨论】:

标签: javascript reactjs testing jestjs enzyme


【解决方案1】:

仍在等待更好的答案,但感谢此链接https://github.com/airbnb/enzyme/issues/76

能够使用以下代码完成将文本输入到我的表单输入中

it('input fields should be filled correctly', () => {
    const credentials = { username: 'leongaban', password: 'testpass' };
    expect(loginComponent.find('#input-auth-username').length).toBe(1);

    const usernameInput = loginComponent.find('#input-auth-username');
    usernameInput.value = credentials.username;
    expect(usernameInput.value).toBe('leongaban');

    const passwordInput = loginComponent.find('#input-auth-password');
    passwordInput.value = credentials.password;
    expect(passwordInput.value).toBe('testpass');
});

【讨论】:

  • 它对我不起作用。我认为github问题链接,您的答案和问题与此处公开的有点无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 2017-03-11
相关资源
最近更新 更多