【问题标题】:loading service with setTimeout test case not covered in angular 9?使用 Angular 9 中未涵盖的 setTimeout 测试用例加载服务?
【发布时间】:2020-09-27 01:28:40
【问题描述】:

如何在代码覆盖范围未涵盖的代码下方进行测试。 使用 Angular 9 中未涵盖的 setTimeout 测试用例加载服务。 我累了,但似乎没有被覆盖。任何人都可以帮我解决我的代码。

加载服务

import { EventEmitter, Injectable, Output } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class LoadingService {
  loaderText: any;
  get showLoader(): any {
    return this._showLoader;
  }
  set showLoader(newData: any) {
    this._showLoader = newData;
  }

  constructor() {}
  @Output() userChangeEvent: EventEmitter<boolean> = new EventEmitter();

  _showLoader: boolean;
  setLoader(isShowLoader) {
    this.userChangeEvent.emit(isShowLoader);
  }

  getLoaderText(): any {
    return this.loaderText;
  }
  setLoaderText(text: any) {
    this.loaderText = text;
  }
}

App.ts

this.loadinSrvc.userChangeEvent.subscribe((user) =>
      setTimeout(() => {
        this.showLoader = {
          text: this.loadinSrvc.getLoaderText() || 'Please wait...',
          isLoader: user,
        };
      })
    );

这是规范文件

it(`should have as showloader configured`, async(() => {
      const app = fixture.debugElement.componentInstance;
      expect(app.showLoader).toEqual({
        isLoader: false,
        text: 'Please wait...',
      });
    }));

【问题讨论】:

    标签: angular typescript unit-testing jasmine karma-jasmine


    【解决方案1】:

    您必须使用fakeAsync 区域方法,并调用flush 来清空宏任务队列,直到它为空。很多花哨的词,但基本上这应该有效:

    it(`should have as showloader configured`, fakeAsync(() => {
      const app = fixture.debugElement.componentInstance;
      flush();
    
      expect(app.showLoader).toEqual({
       isLoader: false,
       text: 'Please wait...',
      });
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多