首页 > web前端 > js教程 > 正文

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

花韻仙語
发布: 2025-10-31 12:01:07
原创
799人浏览过

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

本文深入探讨了一个常见的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 (
        <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).toHaveBeenCalled(); // 此测试通过
    });

    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).toHaveBeenCalled(); // 此测试失败
    });
});
登录后复制

在运行上述测试时,onDownload的测试能够成功通过,但onCancel的测试却失败了,并抛出以下错误:

expect(jest.fn()).toHaveBeenCalled()

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函数。

白瓜面试
白瓜面试

白瓜面试 - AI面试助手,辅助笔试面试神器

白瓜面试40
查看详情 白瓜面试

虽然ChooseLanguageModalProps接口定义了onCancel?: () => void;,使得onCancel成为一个合法的prop,并且我们在测试中也通过<ChooseLanguageModal onCancel={handleCancel} />将其传递给了组件,但组件内部并未实际执行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。这包括两个步骤:

  1. 从props中解构出onCancel函数。
  2. 在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回调未触发导致的测试失败的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号