Search code examples
angularjestjsagora.io

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


I am using the agora web sdk (agora-rtc-sdk-ng Version 4.8.2 from npm) as an import in an angular project. The sdk works fine and can be used just like expected. But when I try to run tests with Jest I get the following error message: "ReferenceError: ImageData is not defined" for the following Import statement

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

Has anyone experienced the same or has any idea how to fix this error?

Here is the complete error message:

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)```

Solution

  • 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 this answer.

    For example, if you need window.ImageData to be available on the window add this to your package.json:

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

    And in tests/setup.js:

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

    Alternatively, you can expect the error and handle it in your test.