首页 > 解决方案 > Angular - 偶尔失败的单元测试(路由器)

问题描述

我有一个 Angular 8 应用程序,它使用路由器在一些主要组件之间切换。现在我做了一些单元测试,有时测试都通过了,但有时一两个都失败了——总是出于同样的原因。

这是我通过运行 ng test 得到的输出(当测试失败时):

Chrome 80.0.3987 (Windows 10.0.0): Executed 32 of 34 ERROR (0 secs / 0.819 secs)
Chrome 80.0.3987 (Windows 10.0.0) ERROR
  An error was thrown in afterAll
  Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'overview'
  Error: Cannot match any routes. URL Segment: 'overview'
      at ApplyRedirects.noMatchError (http://localhost:9876/_karma_webpack_/node_modules/@angular/router/fesm2015/router.js:4295:1)
      at CatchSubscriber.selector (http://localhost:9876/_karma_webpack_/node_modules/@angular/router/fesm2015/router.js:4259:1)
      at CatchSubscriber.error (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/operators/catchError.js:29:1)
      at MapSubscriber._error (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:75:1)
      at MapSubscriber.error (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:55:1)
      at MapSubscriber._error (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:75:1)
      at MapSubscriber.error (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:55:1)
      at MapSubscriber._error (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:75:1)
      at MapSubscriber.error (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:55:1)
Chrome 80.0.3987 (Windows 10.0.0): Executed 34 of 34 ERROR (1.167 secs / 0.907 secs)

我已将RouterTestingModule包含在每个测试文件的导入数组中,其中相应的组件以任何方式使用路由器。像这样的例子:

describe('FeedbackComponent', () => {
  let component: FeedbackComponent;
  let fixture: ComponentFixture<FeedbackComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FeedbackComponent, OverviewHeaderComponent ],
      imports: [FormsModule, RouterTestingModule, HttpClientTestingModule]
    })
    .compileComponents();
  }));

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

有人遇到过这种问题吗?或者知道为什么这会随机失败?已经非常感谢你了:)

标签: angularunit-testingjasminekarma-jasmineweb-frontend

解决方案


尝试做:

RouterTestingModule.withRoutes(
        [{path: 'overview', component: FeedbackComponent}]
      )

真的,FeedbackComponent可以是您创建的任何虚拟组件。这可能会解决您的问题,但我不确定它将如何扩展。看来你有一个更大的潜在问题。我看到错误被抛出afterAll,你有任何afterAll钩子吗?他们有什么有趣的事情吗?


推荐阅读