简体   繁体   中英

Jest/Enzyme testing Form component

I am testing the form component on my react app. I am getting a similar error as the unresolved post here ( Testing form input in jest and enzyme ).

I tried 2 different methods for form.test.js below, both aren't giving me passing tests.

//simple form component

import React from "react";
import Checkbox from "../checkbox/checkbox.component";
import { withRouter } from 'react-router-dom';

class Form extends React.Component {
    constructor(props){
        super(props);

        this.state={
            fullName:"",
            email:""
            }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);

    }

    handleChange(event){
        this.setState({[event.target.name]: event.target.value});
    }


    handleSubmit = async event => {
        event.preventDefault();
    
        try {
          const requestData = {
            method: 'POST',
            headers:{
               'Content-Type': 'application/json'
            },
            body: JSON.stringify(this.state)
          };
          const response = await fetch('http://localhost:5000/results', requestData);
          this.props.history.push('/thankyou');
        
         } 
         catch (error) {
            console.log(error);
         }
    }

    render(){
        return(
          <div>
             <form onSubmit={this.handleSubmit}>
                 <label>
                    Full Name
                </label>
                <input
                    type="text"
                    value={this.state.fullName}
                    onChange={this.handleChange}
                    name="fullName"
                    required
                    />
            
                <br></br>
                <label>
                    Email
                </label>
                    <input
                        type="email"
                        value={this.state.email}
                        onChange={this.handleChange}
                        name="email"
                        required
                    />
                <br></br>
                <input type="submit" value="Submit"/>
            
             </form>     
            </div>
        );
    }
}

export default withRouter(Form);

Method #1:

Expected: "Hello World"
Received: ""
//form.test.js



import React from 'react';
import Form from './form.component';
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom'; 

describe ('Form', () => {
    let wrapper;

    beforeEach(() => {
        wrapper = mount(
        <MemoryRouter>
            <Form/>
        </MemoryRouter>
        )
    });


    it('should capture fullname correctly onChange', () => {

        const input = wrapper.find('input').at(0);
        input.simulate('change', {
                    target: { value : 'Hello World'}
                });
        expect(input.instance().value).toEqual("Hello World")

})

});

Method #2: Resource - https://www.mydatahack.com/unit-testing-react-form-with-jest-and-enzyme/

TypeError: Cannot read property 'fullName' of null
//form.test.js

import React from 'react';
import Form from './form.component';
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom'; 

describe ('Form', () => {
    let wrapper;

    beforeEach(() => {
        wrapper = mount(
        <MemoryRouter>
            <Form/>
        </MemoryRouter>
        )
    });


    it('should capture fullname correctly onChange', () => {

        const input = wrapper.find('input').at(0);
        input.instance().value = "Hello World";
        input.simulate('change');
        expect(wrapper.state().fullName).toEqual('Hello World');

})

});

It looks like you have missed to add name as you simulate change event in your 1st attempt.

It would work as you add the name as part of payload of event as following:

input.simulate('change', {
  // without the `name`, the eval (`[event.target.name]`) will result in void 0
  target: { value: 'Hello World', name: 'fullName' }
});

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