简体   繁体   中英

How to input text into form during React/Jest/Enzyme Shallow Rendering testing?

I have the following form:

<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>

My current test

The first test passes, it's the 2nd test I'm unable to write at the moment.

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

    });
});

I want to test a form submission, however I first need to enter in text into the #input-auth-username and the #input-auth-password input fields.

How do you do that with Enzyme ?

Still waiting on a better answer, but thanks to this link https://github.com/airbnb/enzyme/issues/76

Was able to accomplish text being entered into my form's inputs using the following code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM