You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest单元测试中出现TypeError: (0 , _ToastComponent.showToast) is not a function的问题求助

Jest单元测试中出现TypeError: (0 , _ToastComponent.showToast) is not a function的问题求助

大家好,我遇到了一个Jest测试的问题,想请大家帮忙看看:

我本地用npm start启动应用的时候一切正常,但运行npm test跑单元测试时,总是抛出下面这个错误:

TypeError: (0 , _ToastComponent.showToast) is not a function

      20 |         } = error;
      21 |         if (response && msg) {
    > 22 |             showToast(msg, "toast toast-danger", "alert", true, getToastTimeLimit());
         |                      ^
      23 |         } else {
      24 |             showToast("Internal server error!", "toast toast-danger", "alert", true, getToastTimeLimit());
      25 |         }

下面是我的相关配置和代码:

1. jest-setup.js 文件

import '@testing-library/jest-dom';

2. package.json 配置

{
  "name": "test-ui",
  "private": true,
  "version": "1.0.0",
  "scripts": {
    "start": "vite",
    "test": "jest",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/plugin-transform-runtime": "^7.25.9",
    "@trimble-oss/modus-icons": "^1.15.0",
    "@trimble-oss/modus-react-components": "^0.36.0-react18",
    "@trimbleinc/modus-react-bootstrap": "^1.2.4",
    "axios": "^1.7.7",
    "date-fns": "^4.1.0",
    "express": "^4.21.1",
    "gulp": "^5.0.0",
    "jwt-decode": "^3.1.2",
    "react": "^18.3.1",
    "react-bootstrap": "^2.10.4",
    "react-dom": "^18.3.1",
    "react-router-dom": "^6.26.1"
  },
  "devDependencies": {
    "@babel/core": "^7.26.0",
    "@babel/preset-env": "^7.26.0",
    "@babel/preset-react": "^7.8.3",
    "@testing-library/dom": "^9.3.4",
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^14.3.1",
    "@vitejs/plugin-react": "^3.1.0",
    "babel-jest": "^27.5.1",
    "babel-loader": "^8.0.6",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.19.0",
    "eslint-plugin-react-hooks": "^1.7.0",
    "jest": "^27.5.1",
    "jest-css-modules-transform": "^4.4.2",
    "vite": "^4.5.5"
  }
}

3. 抛出错误的业务代码

这是调用showToast的那个函数:

import http, { getRefreshToken } from "./httpService";
import { showToast } from "../components/common/ToastComponent";
import { showSpinner } from "../components/common/SpinnerComponent";
import { getToastTimeLimit } from "../properties/properties";
import { loadConfig } from "../utils/util";

export async function getAccessToken(username, password) {
    const { hostName } = await loadConfig();
    try {
        const response = await http.post(`${hostName}/test/test`, { username, password });
        console.log("Login successful :-)");
        return response;
    } catch (error) {
        const {
            response: {
                data: { msg },
            },
            response,
        } = error;
        if (response && msg) {
            showToast(msg, "toast toast-danger", "alert", true, getToastTimeLimit());
        } else {
            showToast("Internal server error!", "toast toast-danger", "alert", true, getToastTimeLimit());
        }
        showSpinner(false);
        throw error;
    }
}

4. 触发错误的测试用例代码

test("calling the api end point for a invalid input", async () => {
    const checkLoggedInSpy = jest
      .spyOn(http, "checkLoggedIn")
      .mockReturnValue(true);
    renderComponent();

    axios.post.mockRejectedValue({
      response: {
        data: {
          msg: "Invalid username or password",
        },
      },
    });

    const usernameInput = screen.getByPlaceholderText("Username");
    const passwordInput = screen.getByPlaceholderText("Password");
    fireEvent.change(usernameInput, { target: { value: "test" } });
    fireEvent.change(passwordInput, { target: { value: "test" } });

    await waitFor(() => {
      const loginButton = screen.getByTestId("login-btn");
      fireEvent.click(loginButton);

      expect(axios.post).toHaveBeenCalledWith(expect.any(String), {
        username: "test",
        password: "test",
      });
    });

    checkLoggedInSpy.mockRestore();
  });

我之前试过用AI工具排查,它建议我mock showToast函数,但我希望这个函数能实际执行,这样才能提高测试覆盖率,所以不想直接mock它。请问有没有办法让Jest正确识别到这个函数,让测试能正常跑起来呢?

备注:内容来源于stack exchange,提问作者sp-sathish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:05:43