
本文深入探讨了一个常见的react组件测试失败案例:当组件的oncancel回调属性被定义但未在内部逻辑中实际调用时,测试会报告tohavebeencalled失败。通过分析组件代码和测试用例,我们揭示了问题的根本原因,并提供了明确的解决方案,即在组件的handlecancel方法中显式调用oncancel属性,确保组件行为与测试预期一致。
问题背景与现象分析
在开发React组件时,我们经常会为组件定义各种回调函数(props),以实现父子组件间的通信。例如,一个模态框组件可能会有onDownload和onCancel等回调。当为这些回调编写单元测试时,我们期望点击相应的按钮能够触发这些回调函数。
考虑以下ChooseLanguageModal组件及其测试用例。该组件包含一个“下载”按钮和一个“取消”按钮,并分别对应handleDownload和handleCancel内部方法。
// ChooseLanguageWindow.react.tsx (部分代码)import React from 'react';import { Button, Modal, ModalFooter } from 'react-bootstrap';// ...其他导入export interface ChooseLanguageModalProps { languageList: SelectOption[]; onDownloadLanguage: (value?: string) => void; onDownload: () => void; onCancel?: () => void; // 定义了onCancel回调,但它是可选的}// ...其他常量和辅助函数export const ChooseLanguageModal = (props: ChooseLanguageModalProps) => { const { languageList } = props; // 注意:这里没有解构onCancel // ...onChangeLanguage 方法 const handleCancel = async () => { // 问题所在:onCancel() 未在此处调用 await hideChooseLanguageModal(); }; const handleDownload = async () => { const { onDownload } = props; onDownload(); // onDownload在此处被调用 await hideChooseLanguageModal(); }; return ( {/* ...ModalHeader 和 ModalBody */} );};
相应的测试代码如下:
// ChooseLanguageWindow.react.test.tsx (部分代码)import { render, fireEvent, screen } from '@testing-library/react';import React from 'react';import { act } from 'react-dom/test-utils';import { ChooseLanguageModal } from '../ChooseLanguageWindow.react';describe('ChooseLanguageModal', () => { // ...languageList 定义 const onDownloadLanguage = jest.fn(); const handleDownload = jest.fn(); const handleCancel = jest.fn(); // Mock onCancel prop test('should call onDownload when download button is clicked', async () => { await act(async () => { render( ); }); const downloadButton = screen.getByText('Download'); fireEvent.click(downloadButton); expect(handleDownload).toHaveBeenCalled(); // 此测试通过 }); test('should call onCancel when cancel button is clicked', async () => { await act(async () => { render( ); }); const cancelButton = screen.getByText('Cancel'); fireEvent.click(cancelButton); expect(handleCancel).toHaveBeenCalled(); // 此测试失败 });});
在运行上述测试时,onDownload的测试能够成功通过,但onCancel的测试却失败了,并抛出以下错误:
expect(jest.fn()).toHaveBeenCalled()Expected number of calls: >= 1Received number of calls: 0
这明确指出,尽管我们模拟了onCancel回调并将其作为prop传递给了组件,但当取消按钮被点击时,这个模拟函数并未被实际调用。
根本原因分析
问题的核心在于ChooseLanguageModal组件内部对onCancel prop的使用方式。回顾handleCancel方法:
const handleCancel = async () => { await hideChooseLanguageModal();};
可以看到,在handleCancel方法中,它只调用了hideChooseLanguageModal来隐藏模态框,但并没有调用从props中接收到的onCancel函数。
虽然ChooseLanguageModalProps接口定义了onCancel?: () => void;,使得onCancel成为一个合法的prop,并且我们在测试中也通过将其传递给了组件,但组件内部并未实际执行props.onCancel()。因此,当测试断言expect(handleCancel).toHaveBeenCalled()时,由于作为prop传入的mock函数handleCancel从未被组件内部调用,测试自然会失败。
与之形成对比的是handleDownload方法,它正确地解构并调用了onDownload prop:
const handleDownload = async () => { const { onDownload } = props; onDownload(); // 正确调用了onDownload prop await hideChooseLanguageModal();};
这解释了为什么onDownload的测试能够成功通过。
解决方案
要解决onCancel测试失败的问题,我们需要修改ChooseLanguageModal组件,确保在handleCancel方法中正确调用onCancel prop。这包括两个步骤:
从props中解构出onCancel函数。在handleCancel方法中调用它。
修改后的ChooseLanguageModal组件代码如下:
// ChooseLanguageWindow.react.tsx (修改后)import React from 'react';import { Button, Modal, ModalFooter } from 'react-bootstrap';import ReactDOM from 'react-dom';import Select from 'controls/Select/Select';import { getModalRoot } from 'sd/components/layout/admin/forms/FvReplaceFormModal/helpers';import { DOWNLOAD_BUTTON_TEXT, CANCEL_BUTTON_TEXT } from 'sd/constants/ModalWindowConstants';import 'sd/components/layout/admin/forms/FvReplaceFormModal/style.scss';import type { SelectOption } from 'shared/types/General';const { Body: ModalBody, Header: ModalHeader, Title: ModalTitle } = Modal;export interface ChooseLanguageModalProps { languageList: SelectOption[]; onDownloadLanguage: (value?: string) => void; onDownload: () => void; onCancel?: () => void;}const HEADER_TITLE = 'Choose language page';const CHOOSE_LANGUAGE_LABEL = 'Choose language';export const ChooseLanguageModal = (props: ChooseLanguageModalProps) => { // 1. 从props中解构出onCancel const { languageList, onCancel } = props; const onChangeLanguage = (value?: string | undefined) => { const { onDownloadLanguage } = props; onDownloadLanguage(value); }; const handleCancel = async () => { // 2. 在这里调用onCancel prop onCancel && onCancel(); // 注意:onCancel是可选的,所以进行条件调用 await hideChooseLanguageModal(); }; const handleDownload = async () => { const { onDownload } = props; onDownload(); await hideChooseLanguageModal(); }; return ( hideChooseLanguageModal()} > {HEADER_TITLE} This project has one or more languages set up in the Translation Manager.
To download the translation in the BRD export, select one language from the drop-down below. English will always be shown as the base language.
If a language is selected, additional columns will be added to display the appropriate translation for labels, rules and text messages.
You may click Download without selecting a language to export the default language.
{CHOOSE_LANGUAGE_LABEL} </Modal
以上就是React组件测试:解决onCancel回调未触发导致的测试失败的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1533969.html
微信扫一扫
支付宝扫一扫