Angular - 使用测试模块和 RouterMock 进行路由器单元测试

Angular - Router unit testing with testing module and RouterMock

我已经阅读了几个关于如何对路由进行单元测试的问题。但没有什么真正适合我的情况。我有一个导航栏组件。有几个 [routerLink]=[...] 当我模拟点击事件时。例如,我想调用 expect(router.navigate).toHaveBeenCalledWith(*path*);

但是我已经在测试设置上失败了:它每次都会抛出我:cannot find root of undefined

测试套件

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

  const router: Router = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        NgbModule.forRoot(),
        RouterTestingModule
      ],
      providers: [
        {provide: Router, useValue: router}
      ],
      declarations: [
        NavbarComponent,
      ]
    })
      .compileComponents();
  }));

  it('should navigate on click - home', () => {
    (<jasmine.Spy>router.navigate).and.stub();
    const debugElm = fixture.debugElement.nativeElement.querySelector('#navLogo');
    debugElm.click();

    expect(router.navigate).toHaveBeenCalledWith(['/stories']);
  });

当我删除 RoutingTestingModule 导入时,它会抛出:Cannot bind to routerLink - 我实际上需要测试。真令人沮丧...有人对此有解决方案吗?

RouterTestingModule 已经提供了模拟 Router 实例,因此无需在测试中显式提供。尝试这样的事情:

describe('NavbarComponent', () => {
  let component: NavbarComponent;
  let fixture: ComponentFixture<NavbarComponent>;
  let navigateSpy: Spy;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        NgbModule.forRoot(),
        RouterTestingModule
      ],
      declarations: [
        NavbarComponent,
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NavbarComponent);
    component = fixture.componentInstance;
    navigateSpy = spyOn(TestBed.get(Router), 'navigate'); // <= init spy 
  });

  it('should navigate on click - home', () => {
    const debugElm = fixture.debugElement.nativeElement.querySelector('#navLogo');
    debugElm.click();

    expect(navigateSpy).toHaveBeenCalledWith(['/stories']); // <= check spy
  });