单元测试角度路由器事件导航结束

时间:2019-09-25 09:00:13

标签: angular

我正在尝试对我的app.component.ts进行单元测试,以监听路由器事件并设置页面标题。我能够测试是否已调用getTitle函数,但我真的挂断了对其余部分的测试。 (我需要100%的线路覆盖率)。也许你可以帮忙。

我的 app.component.ts 看起来像这样(只是相关部分):

export class AppComponent {
  public title = '';

constructor(private router: Router, private titleService: Title) {

    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.title = this.getTitle(this.router.routerState, this.router.routerState.root).join('-');
        this.titleService.setTitle(this.title);
      }
    });
  }

  // collect title data properties from all child routes
  public getTitle(state: any, parent: any) {
    const data: any = [];
    if (parent && parent.snapshot.data && parent.snapshot.data.title) {
      data.push(parent.snapshot.data.title);
    }
    if (state && parent) {
      data.push(... this.getTitle(state, state.firstChild(parent)));
    }
    return data;
  }
}

我当前的 app.component.spec.ts 如下:

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let methodSpy: jasmine.Spy;
  let titleService: Title;

  const eventSubject = new ReplaySubject<RouterEvent>(1);

  const routerMock = {
    navigate: jasmine.createSpy('navigate'),
    events: eventSubject.asObservable(),
    url: 'container'
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [
        AppComponent,
        { provide: Router, useValue: routerMock},
        { provide: Title}
      ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    methodSpy = spyOn(component, 'getTitle');
    fixture.detectChanges();
  });

  // this works
  it('getTitle should have been called', () => {
    eventSubject.next(new NavigationEnd(1, 'container', 'container'));
    expect(methodSpy).toHaveBeenCalled;
  });

  // this gives me a "cannot read property root of undefined" error
  it('page title should be "Container"', () => {
    titleService = TestBed.get(Title);
    expect(titleService.getTitle()).toBe("Container");
  });
});

我也尝试过类似的方法,但是还是没有运气:

it('page title should be "Container"', () => {
  expect(component.title).toEqual("Container");
});

可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您的存根应包含更多道具:

  const routerMock = {
    navigate: jasmine.createSpy('navigate'),
    events: eventSubject.asObservable(),
    url: 'container',
    routerState : { root: { snapshot: { data: { title: 'my stub value' } } } }
  }