如何修复“错误:预期在 'ProxyZone' 中运行,但未找到。” 在摩卡测试中?

Kus*_*han 12 unit-testing mocha.js typescript mocha-webpack angular

我正在尝试使用mochachaiwebpack测试我的英雄之旅 Angular 应用程序。我已经关注了这篇文章并在本指南的帮助下完成了设置并修复了构建错误并启动并运行了测试。

但是,我的测试失败了,除了我不使用async()inbeforeEach钩子的测试用例。

通过测试

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [HeroService, MessageService]
    });
    httpTestingController = TestBed.get(HttpTestingController);

    let mockHeroes = [...mockData];
    let mockHero = mockHeroes[0];
    // let mockId = mockHero.id;

    heroService = TestBed.get(HeroService);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('is created', () => {
    expect(heroService).to.exist;
  });
Run Code Online (Sandbox Code Playgroud)

未通过测试

//imports
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DashboardComponent } from './dashboard.component';
import { HeroSearchComponent } from '../hero-search/hero-search.component';

import { RouterTestingModule } from '@angular/router/testing';
import { HeroService } from '../hero.service';
import { expect } from 'chai';

...

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DashboardComponent, HeroSearchComponent],
      imports: [RouterTestingModule.withRoutes([])],
      providers: [{ provide: HeroService, useValue: heroService }]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).to.exist;
  });
Run Code Online (Sandbox Code Playgroud)

错误堆栈跟踪

1) 仪表盘组件

  "before each" hook for "should be created":
Error: Expected to be running in 'ProxyZone', but it was not found.
 at Function.ProxyZoneSpec.assertPresent (node_modules\zone.js\dist\proxy.js:42:19)
 at runInTestZone (node_modules\zone.js\dist\async-test.js:202:23)
 at D:\Practice\Tour-Of-Heroes\node_modules\zone.js\dist\async-test.js:185:17
 at new ZoneAwarePromise (node_modules\zone.js\dist\zone-node.js:910:29)
 at Context.<anonymous> (node_modules\zone.js\dist\async-test.js:184:20)
Run Code Online (Sandbox Code Playgroud)

我已经尝试过Angular 5 测试:预计将在“ProxyZone”中运行,但未找到因为我认为这是使用mocha 的zone.js 的一些错误,但没有成功。

此外,我尝试按照Mocha 文档进行异步测试,但作为初学者,这对我来说有点困难。

我尝试过谷歌搜索,甚至在stack-overflow 中,但关于使用mocha进行Angular 测试的帖子数量有限。感谢任何帮助解决这个问题。

Fra*_*rzi 31

fakeAsyncdescribe函数中意外使用时遇到了同样的问题。

删除它为我解决了这个问题。

  • 这是我的问题。我无意中将 fackAsync() 放在 describe() 函数周围,而不是放在 it() 函数周围。 (4认同)
  • 一周内第二次我需要打开谷歌才能看到这篇文章 (3认同)

小智 6

这是这个问题的答案。

Angular 5 测试:预计在“ProxyZone”中运行,但未找到

基本上这个异常是由于 async 关键字的位置不正确而导致的。从 beforeEach 中删除 async 并将其添加到“it”上

it('should be created', fakeAsync(() => {
    expect(component).to.exist;
  });
Run Code Online (Sandbox Code Playgroud)