为什么按照 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的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的为什么按照 Angular 官网教程执行简单的测试代码,会遇到expect is not defined的错误消息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mock测试用例_测试用例库
- 下一篇: yarn install 遇到的错误消息