使用Material UI组件的酶单元测试onChange方法

时间:2019-06-17 21:39:22

标签: reactjs jestjs material-ui enzyme

我将如何对该组件的onChange方法进行单元测试。

Comment.js

import React  from "react";
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
const Comment = (props) => (
    <div>

        <form onSubmit={props.onSubmit}>
             <TextField
                type="text"
                id="outlined-multiline-static"
                label="Write A Comment"
                multiline
                name="comment_body"
                value={props.commentBody}
                rows="10"
                fullWidth
                margin="normal"
                variant="outlined"
                onChange={props.commentChange}
            />
            {/* <Button type="submit" variant="outlined" component="span" color="primary">
                Post A Comment
            </Button> */}
             <button type="submit" variant="outlined" component="span" color="primary">
                Write a Comment
            </button>
        </form>
    </div>
)

export default Comment;

这是我对onChange组件进行单元测试的尝试,得到

  

方法“模拟”旨在在1个节点上运行。找到0代替

此行附近

const component = shallow(<Comment commentChange={onChangeMock} commentBody={'test'} />) component.find('input').simulate('change');

Comment.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';

import Comment from './Comment';




describe('Should render <Comment/> component', () => {

    it('Should render form', () => {
        const wrapper = shallow(<Comment/>)
        // wrapper.find('Form').at(0)
        expect(wrapper.find("form")).toHaveLength(1); // checks if there is a form. 

    })

    it('Should render button', () => {
        const wrapper = shallow(<Comment/>)
        expect(wrapper.find('button')).toHaveLength(1);
    })

    it('should check for onChange method', () => {
        // const wrapper = shallow(<Comment onChange={}/>)
        const onChangeMock = jest.fn();
        // const event = {
        //     preventDefualt(){},
        //     target: {
        //         value: 'testing'
        //     }
        // }
        const component = shallow(<Comment commentChange={onChangeMock} commentBody={'test'} />)
        component.find('input').simulate('change');
        expect(onChangeMock).toBeCalledWith('test')
    })



})

Comment组件正在这样的另一个组件中传递:

ImageContainer.js

 state = {
      isComment: false,
      comment_body: ""
    }
    handleCommentChange = (e) => {
        this.setState({
           comment_body: e.target.value
        })             
    }

    commentSubmit = (event, id) => {
        event.preventDefault();
        console.log(this.state.comment_body); // doesn't get console.log
        // note that commentBody is being used for the req.body as well so its called by req.body.commentBody
        const commentBody = this.state.comment_body
        const data = {   
            commentBody,
            id
        }   
        this.props.postComment(data);
        this.setState({
            comment_body: ''
        })

    }

    <Comment onSubmit={(e) => this.commentSubmit(e, img.id)} 
                commentBody={this.state.comment_body } 
                commentChange={this.handleCommentChange}/> 

1 个答案:

答案 0 :(得分:2)

出现错误的原因是,当您调用component.find('input')时,它将返回一个匹配组件的数组,所以您要做的是

  1. component.find('input').at(0).simulate('change')

但是,还有另一种测试方法,这是我的首选方法。

  1. component.find('input').at(0).props().onChange()

下面是使用这两种方法进行测试的正确方法

import React from "react";
import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import Comment from "./Comment";
import TextField from "@material-ui/core/TextField";

Enzyme.configure({ adapter: new Adapter() });

describe("Should render <Comment/> component", () => {
  it("should check for onChange method (1)", () => {
    // const wrapper = shallow(<Comment onChange={}/>)
    const onChangeMock = jest.fn();

    const component = shallow(
      <Comment commentChange={onChangeMock} commentBody={"test"} />
    );
    component
      .find(TextField)
      .at(0)
      .simulate("change", "test");
    expect(onChangeMock).toBeCalledWith("test");
  });

  it("should check for onChange method (2)", () => {
    // const wrapper = shallow(<Comment onChange={}/>)
    const onChangeMock = jest.fn();

    const component = shallow(
      <Comment commentChange={onChangeMock} commentBody={"test"} />
    );
    component
      .find(TextField)
      .at(0)
      .props()
      .onChange();
    expect(onChangeMock).toBeCalled();
  });
});

对于此特定测试,如果仅使用toBeCalled而不是toBeCalledWith,则效果会更好。无需测试调用它的值。