【问题标题】:Jest/Enzyme testing Form componentJest/Enzyme 测试表单组件
【发布时间】:2021-01-08 01:45:34
【问题描述】:

我正在我的 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');

})

});

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-02-12
      • 2018-12-16
      • 2020-01-27
      • 2018-08-30
      • 2019-05-30
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多