简体   繁体   English

使用 Jest / Enzyme 在 React 中的功能组件内部测试方法

[英]Testing method inside functional component in React using Jest / Enzyme

Following is my React Functional Component which I am trying to test using jest / enzyme .以下是我尝试使用jest / enzyme测试的 React 功能组件。

React Functional Component Code - React 功能组件代码 -

export const UserForm = props => {
    const {labels, formFields, errorMessages} = props;
    const [showModal, setShowModal] = React.useState(false);
    const [newId, setNewId] = React.useState('');

    const showModal = () => {
        setShowModal(true);
    }

    const closeModal = () => {
        setShowModal(false);
    };

    const handleSubmit = data => {
        Post(url, data)
            .then(resp => {
                const userData = resp.data;
                setNewId(() => userData.id);
                showModal();
            })
    }

    return (
        <div className="user-form">
            <UserForm
                fields={formFields}
                handleSubmit={handleSubmit}
                labels={labels}
                errors={errorMessages}
            />
            {showModal && <Modal closeModal={closeModal}>
                <div className="">
                    <h3>Your new id is - {newId}</h3>
                    <Button
                        type="button"
                        buttonLabel="Close"
                        handleClick={closeModal}
                        classes="btn btn-close"
                    />
                </div>
            </Modal>}
        </div>
    )
};

Now I am trying to test showModal , closeModal and handleSubmit method, but my tests are failing.现在我正在尝试测试showModalcloseModalhandleSubmit方法,但是我的测试失败了。 Let me know the correct way of testing React Hooks and methods inside functional component.让我知道在功能组件中测试 React Hooks 和方法的正确方法。

My test case -我的测试用例 -

import React from 'react';
import { UserForm } from '../index';
import { shallow } from 'enzyme';

describe('<UserForm />', () => {
    let wrapper;
    const labels = {
        success: 'Success Message'
    };
    const formFields = [];
    const errorMessages = {
        labels: {
            firstName: 'First Name Missing'
        }
    };

    function renderShallow() {
        wrapper = shallow(<UserForm
            labels={labels}
            formFields={formFields}
            errorMessages={errorMessages}
        />);
    }
    it('should render with props(snapshot)', () => {
        renderShallow();
        expect(wrapper).toMatchSnapshot();
    });

    it('should test showModal method', () => {
        const mockSetShowModal = jest.fn();
        React.useState = jest.fn(() => [false, mockSetShowModal]);

        renderShallow();
        expect(mockSetShowModal).toHaveBeenCalledWith(true);
    });
});

Error I am getting -我得到的错误 -

Expected mock function to have been called with:
      [true]
    But it was not called.

Let me know how can i test the showModal , closeModal and handleSubmit methods in a functional component.让我知道如何测试功能组件中的showModalcloseModalhandleSubmit方法。

Generally, functional components in React aren't meant to be tested in that way.通常,React 中的功能组件不应该以这种方式进行测试。 The React team are suggesting that you use the approach of React Testing Library which is more focused on the actual user interface scenarios. React 团队建议您使用更关注实际用户界面场景的 React 测试库的方法。 Instead of testing React component instances, you're testing DOM nodes.您不是在测试 React 组件实例,而是在测试 DOM 节点。

This is the main reason why people are moving away from Enzyme and starting to use RTL, because you want to avoid testing implementation details as much as you can.这是人们远离 Enzyme 并开始使用 RTL 的主要原因,因为您希望尽可能避免测试实现细节。

If you really need to test a certain method, you can export it and test it in isolation from the component.如果确实需要对某个方法进行测试,可以将其导出并与组件隔离进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM