路由器事件未在单元测试中执行

Router events not executing in unit test

我正在尝试测试我的 router.events,但事件没有触发,我不确定为什么。我试过 this 但没有成功。

下面是我的测试设置:

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let router: Router;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule, 
        RouterTestingModule.withRoutes([
          { path: Constants.routes.login, component: LoginComponent },
          { path: Constants.routes.admin.admin, component: AdminWelcomeComponent },
          { path: Constants.routes.user.user, component: HomeComponent }
        ])
      ]
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    router = TestBed.inject(Router);
  });


  it('should be created', () => {
    component.apps = [{ name: '', url: '/test' }];
    component.ngOnInit();

    const event = new NavigationEnd(42, '/test', '/test');
    (TestBed.inject(Router).events as Subject<Event>).next(event);
  });
});

如此屏幕截图所示,订阅未执行。

您还必须确保更改检测是 运行:

/* ... */
fixture.detectChanges();

(TestBed.inject(Router).events as Subject<Event>).next(event);