gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:10:55 35 4
gpt4 key购买 nike

以下是我尝试使用 jest/enzyme 测试的 React 功能组件。

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 Hooks 和方法的正确方法。

我的测试用例-

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 方法。

最佳答案

一般来说,React 中的功能组件不打算以这种方式进行测试。 React 团队建议您使用 React Testing Library 的方法,它更侧重于实际的用户界面场景。您不是在测试 React 组件实例,而是在测试 DOM 节点。

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

关于javascript - 使用 Jest/Enzyme 在 React 中的功能组件内部测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61050394/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com