我如何在规格测试中模拟ngOnInit中的routeQueryParams

问题描述

失败:无法读取null的属性'queryParams'

我认为这是因为我在ngOnInit()中具有以下内容

  ngOnInit() {
    this.route.queryParams.subscribe(async params => {
      this.userInfo = await JSON.parse(params['user_info']);
    });

到目前为止,我已经尝试使用以下方法构建单元测试:

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

  beforeEach(async(() => {
    routeStub = null;

    Testbed.configureTestingModule({
      declarations: [ AddItineraryPage ],imports: [IonicModule.forRoot(),FormsModule,ReactiveFormsModule,RouterTestingModule],providers: [
        {provide: ActivatedRoute,useValue: routeStub}
      ]
    }).compileComponents();

    fixture = Testbed.createComponent(AddItineraryPage);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should create',() => {
    routeStub.queryParams = {
    displayName: '',dateOfBirth: '',email: '',photos: [],location: '',bio: '',intDestination: [],userId: ''};

    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(component).toBeTruthy();

    });
  });
});

解决方法

无法读取null的属性'queryParams'

因此,在queryParams对象上调用属性routeStub时,该属性为null。您将routeStub初始化为null,因此很有意义。 ngOnInit()在您第一次致电fixture.detectChanges()时被呼叫,因此您需要在致电之前给routeStub 分配一些东西。

同样在代码中,您在subscribe()上调用queryParams,因此您需要为该属性分配类似于Observable的对象。您可以使用Observable来使用实际的Observable.of()

所以您的测试代码应该更像

beforeEach(async(() => {
  routeStub = null;
  ...
  fixture = TestBed.createComponent(AddItineraryPage);
  component = fixture.componentInstance;
  // remove fixture.detectChanges() as it calls ngOnInit()
}));

it('should create',() => {
  routeStub = {
    queryParams: of({
      user_info: '{
        "displayName": "UserName"
      }'
      // not sure why you are calling `JSON.parse()`
      // but if you are doing that,then user_info should
      // be a JSON string
    })
  };

  fixture.detectChanges();
  fixture.whenStable().then(() => {
    expect(component.userInfo.displayName).toBe('UserName');
  });
});