How can I fix this error "ReferenceError: ImageData is not defined" when using agora-rtc-sdk-ng and running Jest unit tests?

How can I fix this error "ReferenceError: ImageData is not defined" when using agora-rtc-sdk-ng and running Jest unit tests?

我正在使用 agora web sdk(来自 npm 的 agora-rtc-sdk-ng 版本 4.8.2)作为 angular 项目中的导入。该 sdk 工作正常,可以像预期的那样使用。但是当我尝试使用 Jest 进行 运行 测试时,我收到以下错误消息:"ReferenceError: ImageData is not defined" for the following Import statement

import AgoraRTC, { IAgoraRTCRemoteUser } from 'agora-rtc-sdk-ng';

有没有人有过同样的经历或知道如何解决这个错误?

完整的错误信息如下:

FAIL  src/app/modules/news/components/news-article/news-article.component.spec.ts
  ● Test suite failed to run

    ReferenceError: ImageData is not defined

      11 | import { selectUserProfile } from '@core/selectors/user.selectors';
      12 | import { AppState } from '@core/reducers';
    > 13 | import AgoraRTC, { IAgoraRTCRemoteUser } from 'agora-rtc-sdk-ng';
         | ^
      14 | import { UserProfile } from '@core/models/user.model';
      15 |
      16 | export interface Meeting {

      at node_modules/agora-rtc-sdk-ng/AgoraRTC_N-production.js:17:65778
      at node_modules/agora-rtc-sdk-ng/AgoraRTC_N-production.js:5:84
      at Object.<anonymous> (node_modules/agora-rtc-sdk-ng/AgoraRTC_N-production.js:5:203)
      at Object.<anonymous> (src/app/core/services/meeting.service.ts:13:1)
      at Object.<anonymous> (src/app/shared/components/meeting/meeting.component.ts:2:1)
      at Object.<anonymous> (src/app/shared/components/index.ts:32:1)
      at Object.<anonymous> (src/app/shared/shared.module.ts:7:1)
      at Object.<anonymous> (src/app/modules/reactions/reactions.module.ts:7:1)
      at Object.<anonymous> (src/app/modules/news/components/news-article/news-article.component.spec.ts:16:1)```

ImageData isn't part of the test environment used by Jest. You can create a mock definition for ImageData yourself. You can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run as described in .

例如,如果您需要 window.ImageData 在 window 上可用,请将此添加到您的 package.json:

"jest": {
    "setupTestFrameworkScriptFile": "tests/setup.js"
}

并且在 tests/setup.js 中:

Object.defineProperty(window, 'ImageData', { value: 'yourValue' });

或者,您可以预期错误并在测试中处理它。