Angular and jasmine:点击按钮后如何避免默认路由测试特定路由

Angular and jasmine: how to avoid default route to test a specific route after clicking a button

我想测试一个使用路由器导航到另一个页面的方法,该方法的名称是 goToView():

  goToView(): void {
    this.router.navigate(['../'+this.view],{relativeTo:this.activeRoute})
  }

在我的规范中 class 我添加了这个:

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [HomeRedirectionBoxComponent],
      imports: [RouterTestingModule.withRoutes(appRoutes)],
    }).compileComponents();

    fixture = TestBed.createComponent(HomeRedirectionBoxComponent);
    component = fixture.componentInstance;

    router = TestBed.get(Router);
    location = TestBed.get(Location);
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should navigate to dashboard', fakeAsync(  () =>  {
    const navigateSpy = spyOn(router, 'navigate');
     component.goToView();
    expect(navigateSpy).toHaveBeenCalledWith(['/dashboard']);
  }));
});

失败的方法:

  it('should navigate to dashboard', fakeAsync(  () =>  {
    const navigateSpy = spyOn(router, 'navigate');
     component.goToView();
    expect(navigateSpy).toHaveBeenCalledWith(['/dashboard']);
  }));

错误信息:

问题是,当我第一次加载我的应用程序时,我重定向到“/homePage”,在我配置路由和重定向的 AppRouteModule 下方:

const appRoutes: Routes = [
  { path: '', redirectTo: '/homePage', pathMatch: 'full' },
  { path: 'homePage', component: HomePageComponent },
  { path: 'dashboard', component: DashboardComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

export default appRoutes;

如何在只点击goToView()方法时设置特定的spy?

试试这个(在评论后面加上!!):

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [HomeRedirectionBoxComponent],
      //!! remove withRoutes, it is not necessary for the test to know about your routes
      imports: [RouterTestingModule],
    }).compileComponents();

    fixture = TestBed.createComponent(HomeRedirectionBoxComponent);
    component = fixture.componentInstance;

    router = TestBed.get(Router);
    location = TestBed.get(Location);
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should navigate to dashboard', fakeAsync(  () =>  {
    const navigateSpy = spyOn(router, 'navigate');
    component.goToView();
    //!! get the first argument
    const firstArg = navigateSpy.calls.mostRecent().args[0];
    //!! expect ['../dashboard'] to contain 'dashboard'
    expect(firstArg[0]).toContain('dashboard');
  }));
});