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

时间:2020-04-05 22:29:46

标签: javascript reactjs ecmascript-6 jestjs enzyme

以下是我正在尝试使用jest / enzyme测试的我的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>
    )
};

现在我正在尝试测试showModalcloseModalhandleSubmit方法,但是我的测试失败了。让我知道测试功能组件内部的React Hook和方法的正确方法。

我的测试用例-

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

我遇到错误-

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

让我知道如何在功能组件中测试showModalcloseModalhandleSubmit方法。

1 个答案:

答案 0 :(得分:0)

通常,React 中的功能组件不应该以这种方式进行测试。 React 团队建议您使用 React 测试库的方法,它更侧重于实际的用户界面场景。您正在测试 DOM 节点,而不是测试 React 组件实例。

这是人们远离 Enzyme 并开始使用 RTL 的主要原因,因为您想尽可能避免测试实现细节。

如果你真的需要测试某个方法,你可以将它导出并与组件隔离测试。