首页 > 解决方案 > 未找到 Angular 返回路线的 Jasmine 单元测试

问题描述

我最近升级到 Angular 9.1.0-rc.2,一切看起来都正常。我能够在本地和服务器上正常提供应用程序,但是在运行 jasmine 单元测试时,每次测试的随机组件都会出现以下错误:

    Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'not-found'
    Error: Cannot match any routes. URL Segment: 'not-found'
        at ApplyRedirects.noMatchError (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/@angular/router/fesm2015/router.js:4327:1)
        at CatchSubscriber.selector (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/@angular/router/fesm2015/router.js:4291:1)
        at CatchSubscriber.error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/operators/catchError.js:29:1)
        at MapSubscriber._error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/Subscriber.js:75:1)
        at MapSubscriber.error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/Subscriber.js:55:1)
        at MapSubscriber._error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/Subscriber.js:75:1)
        at MapSubscriber.error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/Subscriber.js:55:1)
        at MapSubscriber._error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/Subscriber.js:75:1)
        at MapSubscriber.error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/Subscriber.js:55:1)
        at ThrowIfEmptySubscriber._error (http://localhost:9876/Users/asithadesilva/Sites/my-project/node_modules/rxjs/_esm2015/internal/Subscriber.js:75:1)
    error properties: Object({ rejection: Error: Cannot match any routes. URL Segment: 'not-found', promise: [object Promise], zone: Zone({ _parent: Zone({ _parent: Zone({ _parent: Zone({ _parent: null, _name: '<root>', _properties: Object({  }), _zoneDelegate: ZoneDelegate({ _taskCounts: Object({ microTask: 0, macroTask: 0, eventTask: 0 }), zone: <circular reference: Object>, _parentDelegate: null, _forkZS: null, _forkDlgt: null, _forkCurrZone: null, _interceptZS: null, _interceptDlgt: null, _interceptCurrZone: null, _invokeZS: null, _invokeDlgt: null, _invokeCurrZone: null, _handleErrorZS: null, _handleErrorDlgt: null, _handleErrorCurrZone: null, _scheduleTaskZS: null, _scheduleTaskDlgt: null, _scheduleTaskCurrZone: null, _invokeTaskZS: null, _invokeTaskDlgt: null, _invokeTaskCurrZone: null, _cancelTaskZS: null, _cancelTaskDlgt: null, _cancelTaskCurrZone: null, _hasTaskZS: null, _hasTaskDlgt: null, _hasTaskDlgtOwner: null, _hasTaskCurrZone: null }) }), _name: 'ProxyZone', _properties: Object({ ProxyZo ...

这是我设置路由的方式: app-routing.module.ts

import { MetaGuard } from '@ngx-meta/core';
import { UserModule } from './modules/user/user.module';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoggedInGuard } from 'ngx-auth-firebaseui';

import { AdminGuard } from '@shared/guards/admin.guard';
import { CourseModule } from './modules/course/course.module';
import { AdminModule } from './modules/admin/admin.module';
import { PagesModule } from './pages/pages.module';

const routes: Routes = [
  {
    path: '',
    loadChildren: async (): Promise<PagesModule> =>
      import('./pages/pages.module').then((m: { PagesModule: PagesModule }) => m.PagesModule)
  },
  {
    canActivateChild: [MetaGuard],
    path: 'admin',
    loadChildren: async (): Promise<AdminModule> =>
      import('./modules/admin/admin.module').then((m: { AdminModule: AdminModule }) => m.AdminModule),
    canActivate: [LoggedInGuard, AdminGuard]
  },
  {
    path: 'course',
    loadChildren: async (): Promise<CourseModule> =>
      import('./modules/course/course.module').then((m: { CourseModule: CourseModule }) => m.CourseModule),
    data: {
      title: 'Course'
    }
  },
  {
    path: '**',
    redirectTo: '/not-found',
    data: {
      title: 'Page Not Found'
    }
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled'
    })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

页面路由.module.ts

import { NotFoundComponent } from './not-found/not-found.component';
import { HomeComponent } from './home/home.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'not-found',
    component: NotFoundComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class PagesRoutingModule {}

app.module.ts

@NgModule({
  declarations: [AppComponent],
  imports: [
    CommonModule,
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MetaModule.forRoot({
      provide: MetaLoader,
      useFactory: metaFactory
    }),
    FirebaseModule,
    SharedModule,
    Angulartics2Module.forRoot({
      gst: {
        trackingIds: [environment.googleAnalytics]
      }
    })
  ],
  bootstrap: [AppComponent]
})

在实际调用此路由的组件中: this.router.navigate(['not-found']);

我尝试过的事情:

请注意,当我提供应用程序时,我可以访问未找到的页面。我有点坚持这一点,并会感谢任何可能导致此问题的提示。

标签: javascriptangulartypescriptjasminekarma-jasmine

解决方案


由于这里的答案,我似乎能够解决这个问题:https ://stackoverflow.com/a/45315961/1432248

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([{ path: 'not-found', component: NotFoundComponent }]),
        ...,
      ],
      declarations: [..., NotFoundComponent],
    }).compileComponents();
  }));

编辑您的 RouterTestingModule 并使用withRoutes并添加缺少的路由的路径和组件。原始答案详细解释了为什么会发生这种情况。


推荐阅读