【问题标题】:Angular: How can I test component which uses 'getCurrentNavigation'?Angular:如何测试使用“getCurrentNavigation”的组件?
【发布时间】:2020-09-04 23:20:18
【问题描述】:

Angular9

我想使用 jasmine/karma 测试组件。 但是我找不到在具有路由参数的组件上编写测试的方法(使用 getCurrentNavigation )。

实际组件如下

import { Router } from '@angular/router';

export class myComponent implements OnInit {
  // parameters from previous page
  param1: param1model;
  param2: param2model;
  param3: param3model;

  constructor(
    private router: Router,
     ....
  ) {
    if (this.router.getCurrentNavigation().extras.state.data != undefined) {
      this.param1 = this.router.getCurrentNavigation().extras.state.data.aaa;
      this.param2 = this.router.getCurrentNavigation().extras.state.data.bbb;
      this.param3 = this.router.getCurrentNavigation().extras.state.data.ccc;
    }
  }

当前的测试代码是

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { myComponent } from './myComponent';
import { RouterTestingModule } from '@angular/router/testing';

describe('myComponent', () => {
  let component: myComponent;
  let fixture: ComponentFixture<myComponent>;
  let router: jasmine.SpyObj<Router>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule, RouterTestingModule],
      declarations: [myComponent],

    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(myComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  afterEach(() => {
    TestBed.resetTestingModule();
  });

   it('should create', () => {
     expect(component).toBeTruthy();
   });
});

如果我运行测试,我得到了

TypeError:无法读取 null 的属性“附加”

而且我知道它应该显示出来,因为这个 myComponent 必须接收参数 (param1,param2,param3)。

但我不知道如何接收这些参数。 在 Angular 官方文档中,我找不到任何关于这种情况的指南。

如果有人愿意与我分享知识,我将不胜感激

【问题讨论】:

    标签: angular testing


    【解决方案1】:

    为这个函数添加一个带有模拟响应的间谍

    spyOn(router, 'getCurrentNavigation').and.returnValue(return something here);
    // check what real function returns line 
    
    /*something like this
    {extras:{
       state:{
             data: 3
             }
         }
    }*/
    

    现在它不应该给出这个错误

    【讨论】:

    • 在这种情况下,我得到了错误。 missing the following properties from type 'Navigation': id, initialUrl, extractedUrl, trigger, previousNavigation是因为let router: jasmine.SpyObj&lt;Router&gt;;吗?
    猜你喜欢
    • 2021-10-15
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2022-01-15
    • 2017-06-18
    相关资源
    最近更新 更多