笑话/酵素测试表格组件

时间:2020-09-21 23:29:09

标签: javascript reactjs jestjs enzyme

我正在测试我的React应用程序中的表单组件。 我收到的错误与此处未解决的帖子(Testing form input in jest and enzyme)类似。

我在下面的form.test.js中尝试了2种不同的方法,但都没有通过测试。

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

方法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")

})

});

方法2: 资源-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');

})

});

1 个答案:

答案 0 :(得分:0)

您似乎在第一次尝试模拟name事件时错过了添加change的机会。

当您将name添加为事件有效负载的一部分时,它将起作用,如下所示:

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