在Angular中测试router.navigate以调用ngOnInit

时间:2017-07-03 11:21:44

标签: angular unit-testing

我们有一个Angular App,并且按照惯例,我们在ngOnInit组件中进行了服务调用。我们正在编写单元测试,我们尝试编写的测试之一就是:

if("should get years when navigating to '/'")

事情是没有使用router.navigate调用ngOnInit我一直在阅读,看起来该组件的实例仍处于活动状态且之前已调用ngOnInit,但是如果我打电话给fixture.detectChanges()它有效。那么为什么它不适用于router.navigate

这是我们的测试:

  it("should get years only once when navigating to '/'", fakeAsync(() => {
    // Act
    router.navigate([""]);

    tick();

    // Assert
    expect(getAvailableYearsSpy).toHaveBeenCalledTimes(1);
  }));

这是我们正在测试的组件:

@Component({
  selector: "app-component-under-test",
  templateUrl: "./app-component-under-test.html",
  styleUrls: ["./app-component-under-test.scss"]
})
export class ComponentUnderTest implements OnInit {
  public years: Array<number> = [];
  public selectedYear: number;

  constructor(
    private componentUnderTestService: ComponentUnderTestService,
    private router: Router,
    private activatedRoute: ActivatedRoute) {
  }

  public ngOnInit(): void {
    let year = Number(this.activatedRoute.snapshot.params.year) || undefined;

    this.getYears(1, year);
  }

  private getYears(contractId: number, defaultYear?: number): Promise<number> {
    return this.componentUnderTestService.getAvailableYears(contractId).then((years) => {
      this.selectedYear =  defaultYear || years[0];
      this.years = years;

      return this.selectedYear;
    });
  }
}

这是我们的规范:

describe("ComponentUnderTest", () => {
  let component: ComponentUnderTest;
  let fixture: ComponentFixture<ComponentUnderTest>;
  let service: ComponentUnderTestService;

  let getAvailableYearsSpy;

  let router: Router;
  let location: Location;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        ComponentUnderTestModule,
        RouterTestingModule.withRoutes(componentUnderTestRoutes)
      ]
    });

    fixture = TestBed.createComponent(ComponentUnderTest);

    service = fixture.debugElement.injector.get(ComponentUnderTestService);

    getAvailableYearsSpy = spyOn(service, "getAvailableYears").and.returnValue(Promise.resolve([2017, 2018, 2019]));

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

    component = fixture.componentInstance;
  });

  it("should get years and PrognoseMeldung only once when navigating to '/'", fakeAsync(() => {
    // Act
    router.navigate([""]);

    tick();

    // Assert
    expect(getAvailableYearsSpy).toHaveBeenCalledTimes(1);
  }));
});

0 个答案:

没有答案