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 即可,速度快且不会依赖第三方库的运行环境。
- 在
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";
- 在
src目录下新建__mocks__/azure-maps-control.ts,写入以下内容:
export const ControlOptions = {}; export const AuthenticationType = { subscriptionKey: "subscriptionKey" };
- 在测试文件顶部添加 Mock 声明,或者直接在
src/setupTests.ts中全局添加:
jest.mock("react-azure-maps"); jest.mock("azure-maps-control");
- 修改测试代码里的选择器逻辑:
test('Should render Map component', () => { render(<Map />); // 把getAllByTestId改成getByTestId const mapDiv = screen.getByTestId(/map-div/i); expect(mapDiv).toBeInTheDocument(); });
方案二:配置 Jest 转译 ESM 包
如果需要在测试中真实渲染地图相关逻辑,可以修改 Jest 配置,指定对两个地图包做转译:
- 安装 react-app-rewired 用于修改 CRA 内置配置(无需 eject):
npm install react-app-rewired --save-dev
- 项目根目录新建
config-overrides.js,写入以下内容:
module.exports = { jest: (config) => { config.transformIgnorePatterns = [ "node_modules/(?!(react-azure-maps|azure-maps-control)/)" ]; return config; } };
- 修改
package.json中的 test 命令:
{ "scripts": { "test": "react-app-rewired test" } }
- 同样修改测试代码中
getAllByTestId为getByTestId即可。
内容的提问来源于stack exchange,提问作者Sarthak Vashisht
相关产品推荐
相关产品推荐

