我被分配为我们团队中的 Angular 应用程序编写单元测试,并且我已经完成了 jest 的配置和设置以及让测试工作起来。但当我们的团队将 Microsoft 的 ApplicationInsights-js 集成到我们的应用程序中时,我的测试开始失败。由于公司政策,我无法分享代码,但我会分享我能分享的内容。
我在 Stack Overflow 中搜索了有关 ApplicationInsights-js 的问题,但没有类似的问题。但是,我在 ApplicationInsights-js 的 GitHub 页面中发现了这个问题。问题是here 。我尝试了几乎所有的解决方案,但没有成功。根据this comment根据我的理解,我尝试将模块更改为tsconfig.json中的不同模块,但没有成功。
这是我的错误堆栈跟踪。
● 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/*"]
}
}
}
This is my ApplicationInsights-js version.
"applicationinsights-js": "^1.0.20"
这已经成为我单元测试的一个阻碍。任何帮助表示赞赏。如果信息不够,我会在遵守公司政策的情况下尽力提供更多信息。
最佳答案
发生这种情况是因为该库是作为 AMD 模块构建的。最新的 SDK 以 UMD 形式提供,因此可以解决此问题。如果您无法升级,您可以使用之前讨论过的几个选项 here
- 使用
if (AppInsights !== undefined) 保护对 appinsights 的每次调用
- (复制自 here ):如果您使用 jest,请将空的
applicationinsights-js.js
文件添加到 __mocks__ 文件夹可以修复此问题。如果您需要模拟applicationinsights-js
功能,您也应该能够在此处执行此操作。 请注意 __mocks__ 区分大小写。有关 Jest 模拟的更多信息,see Jest Mock documentation
关于angular - '引用错误: define is not defined' when testing Angular app with jest using ApplicationInsights-js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56077357/