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

Jest测试导入useAuthenticator报TypeError,咨询依赖Mock方法

问题:CRA+TypeScript项目Jest测试导入useAuthenticator时出现window.URL.createObjectURL错误

问题描述

使用CRA(Create React App)的TypeScript模板创建项目后,执行Jest测试时,只要代码中导入@aws-amplify/ui-react的useAuthenticator,就会抛出错误:TypeError: window.URL.createObjectURL is not a function。移除该导入并注释相关代码后,测试流程可正常执行。已查阅Jest Mock函数文档,但仍不清楚如何Mock这类依赖引发的错误。

相关代码

App组件代码

import { useAuthenticator } from '@aws-amplify/ui-react';

const App = () => {
  const { user } = useAuthenticator((context) => [context.user]);
  return (
    <div>{user?.username}</div>
  );
};

export default App;

测试代码

import App from 'src/App';
import { render, screen } from '@testing-library/react';

describe('First group',()=>{
  test('rendering App component',()=>{
    // App includes 'import { useAuthenticator } from '@aws-amplify/ui-react';'
    render(<App/>)
    screen.debug()
  })
})

错误信息

● Test suite failed to run

    TypeError: window.URL.createObjectURL is not a function

    > 1 | import { useAuthenticator } from '@aws-amplify/ui-react';
        | ^
      2 |
      3 | const App = () => {
      4 |   const { user } = useAuthenticator((context) => [context.user]);

      at define (node_modules/maplibre-gl/dist/maplibre-gl.js:25:43)
      at node_modules/maplibre-gl/dist/maplibre-gl.js:35:1
      at node_modules/maplibre-gl/dist/maplibre-gl.js:3:81
      at Object.<anonymous> (node_modules/maplibre-gl/dist/maplibre-gl.js:6:2)
      at Object.<anonymous> (node_modules/@aws-amplify/ui-react/dist/index.js:1:484)
      at Object.<anonymous> (src/App.tsx:1:1)

已尝试的解决方法

  • 曾在项目根目录添加以下配置文件,但问题未解决:
    jest.setup.js:
    if (typeof window.URL.createObjectURL === 'undefined') {
      window.URL.createObjectURL = jest.fn();
    }
    
    jest.config.js:
    module.exports = {
      setupFilesAfterEnv: ['./jest.setup.js'],
    };
    
  • 更新:遵循CRA规则,在src/setupTests.ts中添加上述polyfill代码后,问题解决,但仍希望了解如何Mock这类依赖错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:20:42