ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-04-13 17:29:46  阅读:173  来源: 互联网

标签:UsefulService defined window karma 测试代码 Angular mock expect


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有