提供Angular Router获取“无法读取未定义的属性'root'”

时间:2019-06-19 15:19:21

标签: angular jasmine karma-jasmine

我正在尝试测试一个按钮,当单击该按钮时,它会导航到我的主页,但是当我向Router类提供Jasmine Spy Object时,出现“ TypeError:无法读取未定义的属性'root' ”。

describe('Error404Component', () =>
{
  let component: Error404Component;
  let fixture: ComponentFixture<Error404Component>;
  const routerSpy = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() =>
  {
    TestBed.configureTestingModule({
      imports: [
        AppModule
      ]
    })
      .compileComponents();
  }));

  beforeEach(() =>
  {
    TestBed.overrideProvider(Router, { useValue: routerSpy });
    fixture = TestBed.createComponent(Error404Component);
    component = fixture.componentInstance;
    fixture.autoDetectChanges();
  });

  fit('should navigate', fakeAsync(() =>
  {
    const buttons = fixture.debugElement.queryAll(By.css('.button_link'));
    expect(buttons).toBeTruthy();

    const homeButton = buttons[0];
    (homeButton.nativeElement as HTMLButtonElement).click();

    fixture.detectChanges();
    tick();

    const spy = routerSpy.navigate as jasmine.Spy;

    expect(spy.calls.any()).toBeTruthy();
    expect(spy.calls.first().args[0][0]).toEqual(HOME_PATH);
  }));

});

1 个答案:

答案 0 :(得分:0)

您应该使用router提供TestBed,configureTestingModule和组件中使用的所有其他服务注入。

 describe('Error404Component', () =>
  {

   class MockRouter {
     navigate = jasmine.createSpy('navigate');
   }
  let component: Error404Component;
  let fixture: ComponentFixture<Error404Component>;
  let routerSpy;

  beforeEach(async(() =>
  {
  routerSpy= new MockRouter();
    TestBed.configureTestingModule({
      imports: [
        AppModule
      ],
      providers: [{ provide: Router, useValue: routerSpy }],
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() =>
  {
    fixture = TestBed.createComponent(Error404Component);
    component = fixture.componentInstance;
    fixture.autoDetectChanges();
  });

  fit('should navigate', fakeAsync(() =>
  {
    const buttons = fixture.debugElement.queryAll(By.css('.button_link'));
    expect(buttons).toBeTruthy();

    const homeButton = buttons[0];
    (homeButton.nativeElement as HTMLButtonElement).click();

    fixture.detectChanges();
    tick();

    const spy = routerSpy.navigate as jasmine.Spy;

    expect(spy.calls.any()).toBeTruthy();
    expect(spy.calls.first().args[0][0]).toEqual(HOME_PATH);
  }));

});