首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从aws导入'useAuthenticator‘-在开玩笑时放大输出"TypeError: window.URL.createObjectURL不是函数“

从aws导入'useAuthenticator‘-在开玩笑时放大输出"TypeError: window.URL.createObjectURL不是函数“
EN

Stack Overflow用户
提问于 2022-10-14 02:18:43
回答 1查看 91关注 0票数 0

我想知道如何嘲笑这种依赖的错误。如果我省略了这个导入并注释掉了相关的源代码,那么测试过程就会很好。已经通过了模拟函数Jest,但不知道我该做什么。

*该项目由CRA创建,并附有模板类型记录。

应用程序组件。

代码语言:javascript
复制
import { useAuthenticator } from '@aws-amplify/ui-react';

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

export default App;

测试代码在这里。

代码语言:javascript
复制
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()
  })
})

错误输出在这里。

代码语言:javascript
复制
  ● 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)

根据幻灯片2的答案,添加了安装和配置文件。但还是会犯错误。两者都位于rootDir。

jest.setup.js

代码语言:javascript
复制
if (typeof window.URL.createObjectURL === 'undefined') {
  window.URL.createObjectURL = jest.fn();
}

jest.config.js

代码语言:javascript
复制
module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js'],
};

更新

这个PJ是由CRA创建的,所以它需要遵循他们的规则。最后,我通过幻灯片说明2的答案和正确的位置来解决这个问题。

src/setupTests.ts

代码语言:javascript
复制
if (typeof window.URL.createObjectURL === 'undefined') {
  window.URL.createObjectURL = jest.fn();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-14 03:17:42

请参阅troubleshooting#jest

在包含Geo组件发布的v2.15.0 of @aws-amplify/ui-react中,Jest测试框架的用户在尝试运行测试时可能会遇到以下错误:

代码语言:javascript
复制
window.URL.createObjectURL is not a function

请按照以下步骤解决此问题。

  1. 导航到或为项目创建Jest安装文件。
  2. 添加以下代码以填充Jest安装文件中无法识别的函数:

jest.setup.js

代码语言:javascript
复制
if (typeof window.URL.createObjectURL === 'undefined') {
  window.URL.createObjectURL = jest.fn();
}

jest.config.js

代码语言:javascript
复制
module.exports = {
  //...
  setupFilesAfterEnv: ['./jest.setup.js'],
  //...
}

当与使用未识别函数的包一起使用jsdom库(Jest的依赖项)时,这是一个已知的问题。见本期

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74063650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档