使用服务调用进行角度测试 ngOnInit

时间:2021-03-23 12:24:53

标签: angular unit-testing jasmine karma-jasmine

我正在使用 jasmine 在 Angular 中学习单元测试。我有一个组件,其中 ngOnInit() 方法具有某些服务调用。下面是我的 ngOnInit() 方法:

ngOnInit() {
    this.componentInteractionService.resetCurrentMenu();
    this.router.paramMap.subscribe(params => {
      this.currentContentUrl = params.get("currentContentUrl");
      let tmp = params.get("contentTitle");
      this.contentSubstitle = params.get("contentSubtitle");
      if (tmp == undefined) {
        let url = this.currentContentUrl;
        this.contentTitle = url.substring(url.lastIndexOf("/") + 1, url.length);
      } 
      else {
        this.contentTitle = tmp;
      }
    });
  }

那么我应该如何测试以覆盖 ngOnInit() 方法的所有行?我的意思是我需要完整的代码覆盖率。 在我的spec.ts中:

it('should call all methods in ngOnInit', () => {
    component.ngOnInit();
    .......
    .......
  });

component.ngOnInit(); 后面应该写什么?请帮忙。我可以测试第一行: this.componentInteractionService.resetCurrentMenu(); 但是如何测试其余的行?

1 个答案:

答案 0 :(得分:0)

试试这个

  TestBed.configureTestingModule({
      declarations: [YourComponenToTest],
      providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            paramMap: of([
             {currentContentUrl: 'ccu/tt'}
             {contentSubtitle: 'cs'},
             {contentTitle: 'ct'}
             ]),
          },
        },
      ]
    });

   it('should call all methods in ngOnInit', () => {
      spyOn(component.componentInteractionService,'resetCurrentMenu')
              .and.returnValue('');
      component.ngOnInit();
      expect(component.currentContentUrl).toBe('ccu/tt');
      // similar for component.contentSubstitle for 'cs'
      // similar for component.contentTitle for 'ct'
    });

   it('should set in 'contentTitle' accordingly in ngOnInit', () => {
      component.route.paramMap = of([
             {currentContentUrl: 'ccu/tt'}
             {contentSubtitle: 'cs'}
             ])
      component.ngOnInit();
      expect(component.currentContentUrl).toBe('ccu/tt');
      // similar for component.contentSubstitle for 'cs'
      // similar for component.contentTitle for 'tt' 
    });

让我知道模拟是否有效