angular - 我如何在规范测试中模拟 ngOnInit() 中的路由 queryParams

标签 angular typescript angular-routing angular-router angular2-testing

失败:无法读取 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();

    });
  });
});

最佳答案

Cannot read property 'queryParams' of null

因此,当在 routeStub 对象上调用属性 queryParams 时,它为 null。您将 routeStub 初始化为 null,因此这是有意义的。 ngOnInit() 在您第一次调用 fixture.detectChanges() 时被调用,因此您需要在之前为 routeStub 分配一些内容 你调用电话。

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

所以你的测试代码应该看起来更像

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

关于angular - 我如何在规范测试中模拟 ngOnInit() 中的路由 queryParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64345423/

相关文章:

javascript - 在我的 Angular 项目中使用 @types/cleave.js 时如何忽略 TS1192?

angular - 无法从路由 URL 读取参数

angular - 如何按照 "action hygiene"指南使用多个 NGRX 操作来执行相同的操作?

angular - 如何在 Angular 5 的垫子菜单叠加层上添加类?

angular - 从 Angular 库加载一个模块而不是加载整个库

javascript - TypeError : . currentPizzaPlace.getPoint 不是函数

Angular,在鼠标事件上用 Canvas 绘制多个矩形

javascript - 如何在 http 拦截器 Angular 中处理/检测取消的请求?

javascript - ng-route 注入(inject)器错误 :modulerr [$injector:modulerr] http://errors. angularjs.org/1.3.14/$injector/modulerr

javascript - 加载 Angular View