新闻中心
React组件测试:解决onCancel回调未触发导致的测试失败

本文深入探讨了一个常见的react组件测试失败案例:当组件的oncancel回调属性被定义但未在内部逻辑中实际调用时,测试会报告toh*ebeencalled失败。通过分析组件代码和测试用例,我们揭示了问题的根本原因,并提供了明确的解决方案,即在组件的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 () => {
cons
t { onDownload } = props;
onDownload(); // onDownload在此处被调用
await hideChooseLanguageModal();
};
return (
<Modal
// ...Modal props
>
{/* ...ModalHeader 和 ModalBody */}
<ModalFooter>
<Button bsStyle="primary" onClick={handleDownload}>
{DOWNLOAD_BUTTON_TEXT}
</Button>
<Button onClick={handleCancel}>{CANCEL_BUTTON_TEXT}</Button>
</ModalFooter>
</Modal>
);
};相应的测试代码如下:
// 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(
<ChooseLanguageModal
// ...其他props
onDownload={handleDownload} // 将mock函数作为onDownload prop传入
onCancel={handleCancel} // 将mock函数作为onCancel prop传入
/>
);
});
const downloadButton = screen.getByText('Download');
fireEvent.click(downloadButton);
expect(handleDownload).toH*eBeenCalled(); // 此测试通过
});
test('should call onCancel when cancel button is clicked', async () => {
await act(async () => {
render(
<ChooseLanguageModal
// ...其他props
onDownload={handleDownload}
onCancel={handleCancel}
/>
);
});
const cancelButton = screen.getByText('Cancel');
fireEvent.click(cancelButton);
expect(handleCancel).toH*eBeenCalled(); // 此测试失败
});
});在运行上述测试时,onDownload的测试能够成功通过,但onCancel的测试却失败了,并抛出以下错误:
expect(jest.fn()).toH*eBeenCalled() Expected number of calls: >= 1 Received number of calls: 0
这明确指出,尽管我们模拟了onCancel回调并将其作为prop传递给了组件,但当取消按钮被点击时,这个模拟函数并未被实际调用。
根本原因分析
问题的核心在于ChooseLanguageModal组件内部对onCancel prop的使用方式。回顾handleCancel方法:
const handleCancel = async () => {
await hideChooseLanguageModal();
};可以看到,在handleCancel方法中,它只调用了hideChooseLanguageModal来隐藏模态框,但并没有调用从props中接收到的onCancel函数。
虽然ChooseLanguageModalProps接口定义了onCancel?: () => void;,使得onCancel成为一个合法的prop,并且我们在测试中也通过
与之形成对比的是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 (
<Modal
show
backdrop="static"
animation={false}
container={getModalRoot()}
onHide={() => hideChooseLanguageModal()}
>
<ModalHeader closeButton>
<ModalTitle>{HEADER_TITLE}</ModalTitle>
</ModalHeader>
<ModalBody>
<div>
<p>This project has one or more languages set up in the Translation Manager.</p>
<p>
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.
</p>
<p>
If a language is selected, additional columns will be added to display the appropriate
translation for labels, rules and text messages.
</p>
<p>You may click Download without selecting a language to export the default language.</p>
</div>
<div>{CHOOSE_LANGUAGE_LABEL}</div>
<div>
<Select
clearable={false}
canEnterFreeText={false}
searchable={false}
options={languageList}
onChange={onChangeLanguage}
/>
</div>
</ModalBody>
<ModalFooter>
<Button bsStyle="primary" onClick={handleDownload}>
{DOWNLOAD_BUTTON_TEXT}
</Button>
<Button onClick={handleCancel}>{CANCEL_BUTTON_TEXT}</Button>
</Modal以上就是React组件测试:解决onCancel回调未触发导致的测试失败的详细内容,更多请关注其它相关文章!
# react
# 的是
# 根本原因
# 未被
# 可选
# 自定义
# 给了
# 复选框
# 回调
# 为什么
# win
# ai
# 回调函数
# app
# bootstrap
# css
# red
# 营销推广五步曲
# 苏州正规网站建设概况
# 服装企业营销推广
# 黑马程序员seo
# 海口推广营销
# 鱼洞网站seo
# 吴桥seo优化贵不贵
# 抖音矩阵SEO计划
# 薯条推广定向营销策略
# 谷歌及谷歌seo
# 容器内
# 拖拽
相关栏目:
【
科技资讯46185 】
【
网络学院92790 】
相关推荐:
qq邮箱发邮件给国外发不出去_QQ邮箱国际邮件发送失败原因与解决
Golang如何使用const iota_Go iota常量计数器讲解
优化HTML表单样式:解决输入框焦点跳动与元素间距问题
俄罗斯搜索引擎Yandex指南 附2025年免登录官网入口
晋江读书网页版在线登录 晋江读书电脑版官网
Win11怎么开启卓越性能模式 Win11电源选项启用高性能释放硬件潜力【方法】
QQ邮箱稳定登录入口_QQ邮箱官方网站网页版使用
批改网学生版PC登录 批改网官网登录系统入口
电脑IP地址怎么查 查看本机IP地址的几种方法
J*aScript map 迭代中检测空数组元素的有效方法
Win11怎么开启高性能模式_Windows 11电源计划优化设置
J*aScript生成器_j*ascript异步迭代
Spring Boot内嵌服务器与J*a EE全栈特性:选择与部署策略
CSS响应式网页如何实现主次模块比例自适应_flex-grow与flex-shrink调整
c++中的std::basic_string的SSO优化_c++短字符串优化深度解析
使用Python高效删除Word宏并转换DOCM为DOCX格式
QQ邮箱正确登录入口_QQ邮箱官方网站使用地址
C++ map遍历方法大全_C++ map迭代器使用总结
哔哩哔哩忘记密码了怎么找回_哔哩哔哩密码找回方法
解决深度学习模型训练初期异常高损失与完美验证准确率问题
Composer的 archive 命令怎么用_快速打包你的PHP项目及其Composer依赖
必由学官方平台入口 必由学在线课堂登录地址
一加Ace 6T支持全新明眸护眼:通过了最严苛的护眼小金标认证
Win10怎么设置静态IP地址 Win10手动配置IP地址步骤【指南】
Excel中VLOOKUP的第四个参数是干什么用的_Excel VLOOKUP第四参数作用解析
漫蛙MANWA漫画主页官方入口 漫蛙漫画最新在线阅读地址
如何在CSS中使用浮动制作导航栏_float实现水平菜单
苹果手机如何防止被恶意App追踪
护手霜蹭到袖口上了如何清洗? 怎样避免留下一圈油印?
高德地图怎么看全景照片_高德地图全景照片浏览教程
如何在J*a中实现统一对象行为接口_项目大型化时的接口规范化
iCloud登录入口网页版 苹果iCloud官网登录
火锅吃太多会怎样 火锅吃太多会上火吗
uc浏览器网页版入口 uc浏览器网页版最新网址
J*a里如何实现线程安全的懒加载单例_懒加载单例实现方法解析
2025年云电脑操作系统体验 | 无需本地硬件,随时随地使用高性能PC
《铁拳8》黑皮辣妹新实机:元气满满的18岁少女!
顺丰国际快递查询 国际件官方查询入口
漫蛙网页登录入口 漫蛙漫画官方授权网址
抖音小游戏合成大西瓜免费秒玩入口链接 抖音小游戏热门合集秒玩网站
QQ邮箱网页版登录入口 QQ邮箱官方在线使用平台
PHP 枚举:根据字符串获取枚举案例的策略与实现
深入理解J*a编译器的兼容性选项:从-source到--release
12306选座系统怎么选连座_12306选座多人连坐操作方法
css子元素高度不一致导致布局错位怎么办_使用align-items:stretch解决高度差异
PHP表单数据传递:如何通过隐藏输入字段获取动态ID
基于动态规划的房屋花卉种植最小成本算法详解
Win10如何清理注册表垃圾 Win10手动清理无效注册表【技巧】
AO3最新官网入口公告_2025AO3镜像站实时查询方法
J*aScript打印功能_j*ascript输出控制


2025-10-31
浏览次数:次
返回列表
t { onDownload } = props;
onDownload(); // onDownload在此处被调用
await hideChooseLanguageModal();
};
return (
<Modal
// ...Modal props
>
{/* ...ModalHeader 和 ModalBody */}
<ModalFooter>
<Button bsStyle="primary" onClick={handleDownload}>
{DOWNLOAD_BUTTON_TEXT}
</Button>
<Button onClick={handleCancel}>{CANCEL_BUTTON_TEXT}</Button>
</ModalFooter>
</Modal>
);
};