其他分享
首页 > 其他分享> > 为什么按照 Angular 官网教程执行简单的测试代码,会遇到expect is not defined的错误消息

为什么按照 Angular 官网教程执行简单的测试代码,会遇到expect is not defined的错误消息

作者:互联网

Angular 官网的代码:

https://angular.io/api/core/Injectable#providedin

在这里插入图片描述

我把这段代码原封不动地拷贝到我的 app.module.ts ,然后执行:

@Injectable()
class UsefulService {
}

@Injectable()
class NeedsService {
  constructor(public service: UsefulService) { }
}

const injector = Injector.create({
  providers:
    [{ provide: NeedsService, deps: [UsefulService] }, { provide: UsefulService, deps: [] }]
});
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);

遇到下面的错误消息:

Uncaught ReferenceError: expect is not defined

奇怪的是,Visual Studio Code 里并没有任何语法错误,而且 expect 的定义也能识别到:

然而运行时,expect 的值无法识别:not available

后来我在 medium 上一篇论文里找到了答案:

https://medium.com/@danielrob/understand-angular-testing-with-jasmine-karma-8d1384962011

realise the difference between the browser environment during a karma run vs that when it is being served by an http server

Karma 运行在浏览器环境上和运行在 HTTP 服务器(server side)是有所差异的。

当运行在浏览器里时,describe,it,expect 这些函数均无法访问。

而运行在服务器上时,能正常访问:

在这里插入图片描述

During a karma run context, the window object has been populated with jasmine and angular-mock functions. Angular-mock came from our ‘karma.conf’ file list. Now that we understand these methods are being exposed on the window object, and where they come from, we are fit use them.

在 Karma 运行上下文,jasmine 和 Angular-mock 相关的函数,被生成并保存在 window 对象上。Angular-mock 来自 karma.conf.

既然弄清楚了原因,也就不再继续纠结 Angular 官网上的代码了,将 expect 改成 console.log 即可。

更多Jerry的原创文章,尽在:“汪子熙”:

标签:UsefulService,defined,window,karma,测试代码,Angular,mock,expect
来源: https://blog.csdn.net/i042416/article/details/115673659