【问题标题】:'ReferenceError: define is not defined' when testing Angular app with jest using ApplicationInsights-js使用 ApplicationInsights-js 开玩笑地测试 Angular 应用程序时出现“ReferenceError:未定义定义”
【发布时间】:2019-09-28 08:22:09
【问题描述】:

我被分配为我们团队中的 Angular 应用程序编写单元测试,并且我已经完成了 jest 的配置和设置,并且让测试工作。但随着我们的团队将 Microsoft 的 ApplicationInsights-js 集成到我们的应用程序中,我的测试开始失败。由于公司政策,我不能分享代码,但我会分享我能分享的。

我在 Stack Overflow 中搜索过有关 ApplicationInsights-js 的问题,但没有类似问题。但是,我在 ApplicationInsights-js 的 GitHub 页面中发现这是一个问题。问题是here。我已经尝试在那里调整几乎所有的解决方案,但没有成功。一位会员this comment表示,据我了解,我尝试在tsconfig.json中将module改成不同的,但没有成功。 p>

这是我的错误堆栈跟踪。

  ● Test suite failed to run

    ReferenceError: define is not defined

      1 | import { Injectable } from '@angular/core';
    > 2 | import { AppInsights } from 'applicationinsights-js';
        | ^
      3 | import { environment } from '../../environments/environment';
      4 |
      5 | @Injectable({

      at Object.<anonymous> (node_modules/applicationinsights-js/bundle/ai.module.js:215:1)
      at Object.<anonymous> (src/app/services/app-insights.service.ts:2:1)
      at Object.<anonymous> (src/app/login/login.component.ts:8:1)
      at Object.<anonymous> (src/app/login/login.component.spec.ts:3:1)

tsconfig.json 文件

{
    "compileOnSave": false,
    "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "esModuleInterop": true,
        "module": "es2015",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "importHelpers": true,
        "target": "es6",
        "types": ["node", "jest"],
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2018", "dom"],
        "paths": {
            "cComponents": ["dist/cComponents"],
            "cComponents/*": ["dist/cComponents/*"]
        }
    }
}


这是我的 ApplicationInsights-js 版本。
"applicationinsights-js": "^1.0.20"


这已成为我的单元测试的阻碍。任何帮助表示赞赏。如果信息不够,我会尽量提供更多信息,遵守公司政策。

【问题讨论】:

    标签: angular unit-testing jestjs azure-application-insights


    【解决方案1】:

    发生这种情况是因为库是作为 AMD 模块构建的。最新的 SDK 以 UMD 形式提供,因此可以解决此问题。如果您无法升级,您可以使用之前讨论过的几个选项here

    1. 使用if (AppInsights !== undefined) 保护对 appinsights 的每次调用
    2. (复制自 here):如果您使用的是 jest,将一个空的 applicationinsights-js.js 文件添加到您的 __mocks__ 文件夹可以解决此问题。如果您需要模拟 applicationinsights-js 功能,您也应该可以在此处执行此操作。 请注意 __mocks__ 区分大小写。更多关于 jest mocks 的信息,see Jest Mock documentation

    【讨论】:

    • 如前所述,applicationinsights-js 版本为 1.0.20。节点包管理器站点显示它是最新版本。我不可能更改保护每个应用洞察调用的源代码。 :(
    • 我还添加了一个空的applicationinsights-js.js 文件,但随后错误消失并自动跳过测试。
    • 我检查了你的 GitHub 存储库,了解到 applicationinsights-web 是这个包的新版本。它是否正确?那么,如果我将 AppInsight 实例语法更改为新版本,它是否能够在 UMD 中编译?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 2021-09-17
    • 2017-11-01
    • 2021-09-06
    • 2020-03-17
    • 2018-06-02
    • 2021-07-17
    相关资源
    最近更新 更多