【问题标题】:Enzyme unit testing onChange method using Material UI Components使用 Material UI Components 的酶单元测试 onChange 方法
【发布时间】:2019-06-20 04:19:33
【问题描述】:

我如何能够对这个组件的 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 组件进行单元测试,得到一个

方法“simulate”意味着在 1 个节点上运行。找到了 0 个

围绕这条线

const component = shallow(&lt;Comment commentChange={onChangeMock} commentBody={'test'} /&gt;) 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}/> 

【问题讨论】:

    标签: reactjs jestjs material-ui enzyme


    【解决方案1】:

    你有这个错误的原因是因为当你调用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。无需测试调用它的值。

    【讨论】:

    • ok 会试试这个,组件看起来是否正常,您在代码中发现的任何其他错误。
    • 我收到 Method “props” is meant to be run on 1 node. 0 found instead. 可能是 Material UI 的错误
    • 因为&lt;Input/&gt;来自material UI
    • @randal 是的,同样的问题,你需要调用 .at 我会更新答案,然后你需要确保 component 是你调用 find 的正确元素
    • 我刚刚导入了 TextField 和 component.find(TextField).props().onChange()
    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 2020-06-09
    • 2020-11-28
    • 1970-01-01
    • 2017-09-24
    • 2016-01-27
    • 2018-04-05
    • 2021-02-11
    相关资源
    最近更新 更多