本文介绍了我如何在规格测试中模拟ngOnInit()中的routeQueryParams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Failed: Cannot read property 'queryParams' of nullat

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

I'm assuming it's because I have the following in ngOnInit():

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

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

So far I've tried constructing my unit test with the following:

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();

    });
  });
});

推荐答案

因此,当在 routeStub 对象上调用属性 queryParams 时,该属性为null.您将 routeStub 初始化为null,因此很有意义.第一次调用 fixture.detectChanges()时会调用 ngOnInit(),因此需要在之前为 routeStub 分配一些内容您拨打了电话.

So when the property queryParams is being called on the routeStub object, it is null. You initialized the routeStub to null, so it makes sense. ngOnInit() gets called the first time you call fixture.detectChanges(), so you need to assign something to the routeStub before you make that call.

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

Also in your code, you call subscribe() on the queryParams, so you will need to assign an Observable-like object to the property. You can just use an actual Observable by using Observable.of().

因此您的测试代码应更像

So your test code should look more like

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');
  });
});

这篇关于我如何在规格测试中模拟ngOnInit()中的routeQueryParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 21:28