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

React项目Jest单元测试无法找到react-azure-maps模块问题求助

问题原因

react-azure-maps 以及依赖的 azure-maps-control 都是 ESM 格式导出的包,Create React App 内置的 Jest 默认不会转译 node_modules 下的 ESM 包,导致测试运行时无法识别模块导出内容。
另外你的测试代码本身存在语法错误:getAllByTestId 返回的是匹配元素的数组,不能直接和 toBeInTheDocument 匹配,需要改成 getByTestId。

解决方案

方案一:Mock 第三方地图库(推荐,单元测试优先选择)

单元测试不需要真实渲染地图组件,直接 Mock 掉整个 react-azure-maps 即可,速度快且不会依赖第三方库的运行环境。

  1. 在 src 目录下新建 __mocks__/react-azure-maps.tsx,写入以下内容:
import type { ReactNode } from "react";

const AzureMapsProvider = ({ children }: { children: ReactNode }) => <>{children}</>;
const AzureMap = () => <div data-testid="azure-map-mock" />;

export { AzureMapsProvider, AzureMap };
export * from "react-azure-maps/dist/types";
  1. 在 src 目录下新建 __mocks__/azure-maps-control.ts,写入以下内容:
export const ControlOptions = {};
export const AuthenticationType = {
  subscriptionKey: "subscriptionKey"
};
  1. 在测试文件顶部添加 Mock 声明,或者直接在 src/setupTests.ts 中全局添加:
jest.mock("react-azure-maps");
jest.mock("azure-maps-control");
  1. 修改测试代码里的选择器逻辑:
test('Should render Map component', () => {
  render(<Map />);
  // 把getAllByTestId改成getByTestId
  const mapDiv = screen.getByTestId(/map-div/i);
  expect(mapDiv).toBeInTheDocument();
});

方案二:配置 Jest 转译 ESM 包

如果需要在测试中真实渲染地图相关逻辑,可以修改 Jest 配置,指定对两个地图包做转译:

  1. 安装 react-app-rewired 用于修改 CRA 内置配置(无需 eject):
npm install react-app-rewired --save-dev
  1. 项目根目录新建 config-overrides.js,写入以下内容:
module.exports = {
  jest: (config) => {
    config.transformIgnorePatterns = [
      "node_modules/(?!(react-azure-maps|azure-maps-control)/)"
    ];
    return config;
  }
};
  1. 修改 package.json 中的 test 命令:
{
  "scripts": {
    "test": "react-app-rewired test"
  }
}
  1. 同样修改测试代码中 getAllByTestId 为 getByTestId 即可。

内容的提问来源于stack exchange,提问作者Sarthak Vashisht

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:15:08