【问题标题】:Angular testing ngOnInit with sevice calls使用服务调用对 ngOnInit 进行角度测试
【发布时间】:2021-03-23 23:44:53
【问题描述】:

我正在使用 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(); 但是如何测试其余的行?

【问题讨论】:

  • 您可以模拟 paramMap 以返回您需要的值。返回一个值,使if 块被覆盖,您可以断言contentTitlecontentSubtitlecurrentContentUrlelse 块也是如此。 stackoverflow.com/questions/45917883/… 这就是你模拟 paramMap 的方式,对你来说,你也需要模拟 params.get
  • @AliF50 if 条件要求 tmp 未定义....但 tmp 是一个 let 变量。如何将 tmp 设置为未定义?
  • 但是tmp 是从params.get('contentTitle') 设置的,您应该在测试中控制它。
  • @DhritimanTamuliSaikia:你介意让我知道我的答案中的任何 cmets 吗?
  • @ShashankVivek 抱歉回复晚了...但发生的事情是我现在被要求使用 Jest 进行测试...所以我在处理 Jest 时面临其他几个问题...没有检查您的代码是否正常工作。

标签: angular unit-testing jasmine karma-jasmine


【解决方案1】:

试试这个

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

让我知道模拟是否有效

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2019-04-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多