如何在内部单元测试代码订阅Angular7单元测试用例

时间:2019-04-25 05:07:22

标签: angular unit-testing observable karma-jasmine subscriber

我想进行单元测试并获得所有代码的覆盖范围,但是我无法获得对subscribe中存在的代码的覆盖范围。我能够监视服务和功能,但是在subscribe内部,我无法进行单元测试并获得代码的覆盖范围。以下是Angular 7代码。

LoadListData(type) {
    this.itemListEnvName = [];
    if (type === 'EnvirnmentList') {
      this.environmentBookingService.getBookedEnv()
        .subscribe(
          (environmentBookingsData: EbEnvironmentBooking[]) => {
            if (environmentBookingsData.length > 0) {
              this.itemListEnvNameList = environmentBookingsData;
              this.itemListEnvName = [];
              this.itemListEnvNameList.forEach(element => {
                const obj = {};
                obj['id'] = element['environmentId'];
                obj['itemName'] = element['environmentName'];
                this.itemListEnvName.push(obj);
                this.generateCheckDisable = false;
              });
            } else {
              this.generateCheckDisable = true;
            }
          },
          (error) => {
            this.showMessage('No Response From Delivery DB API');
          }
        );
    } else {

      this.showMessage('No Response From Delivery DB API');
    }


  }

和单元测试用例中的代码类似

 it('should call getBookedEnv service ', function () {
    const service = TestBed.get(EnvironmentBookingService); // get your service
    spyOn(service, 'getBookedEnv').and.callThrough(); // create spy
    component.LoadListData('EnvirnmentList');
    expect(service.getBookedEnv).toHaveBeenCalledWith();

  });

如何在内部(即

)对测试代码进行单元化
if (environmentBookingsData.length > 0) {
              this.itemListEnvNameList = environmentBookingsData;
              this.itemListEnvName = [];
              this.itemListEnvNameList.forEach(element => {
                const obj = {};
                obj['id'] = element['environmentId'];
                obj['itemName'] = element['environmentName'];
                this.itemListEnvName.push(obj);
                this.generateCheckDisable = false;
              });
            } else {
              this.generateCheckDisable = true;
            }

2 个答案:

答案 0 :(得分:0)

如果要测试subscribe内部的代码,则必须模拟服务调用,然后测试要在subscribe内部修改的组件变量,例如this.itemListEnvNamethis.generateCheckDisable

这可能看起来像这样:

 it('should call getBookedEnv service ', function () {
    const service = TestBed.get(EnvironmentBookingService); // get your service
    spyOn(service, 'getBookedEnv').and.callFake(() => {
      return of([]); // or return a list of bookings in case you want to test the first part of the if statement 
    });
    component.LoadListData('EnvironmentList');
    expect(service.getBookedEnv).toHaveBeenCalledWith();

    // additional tests that verify the inside of the subscribe (change below in case the mocked service returned something)
    expect(component.itemListEnvName).equalTo([]);
    expect(component.generateCheckDisable).equalTo(false);
  });

答案 1 :(得分:0)

您需要模拟服务,并使其返回一个Observable。我在StackBlitz中放了一个简单的示例,展示了一种使用您的代码进行处理的方法。

StackBlitz中的注意事项:

  • 我使用spyObject模拟服务,因此以后无需监视服务。
  • 在此spyObject中,我将内部函数getBookedEnv()的返回值设置为Observable -这允许执行订阅中的代码。
  • 对于任何实际测试,您都应将getBookedEnv()当前返回的空对象替换为一些合理模拟的数据。
  • 请注意provider数组,并在其中将服务替换为spy对象。

这是StackBlitz的描述:

describe('BannerComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  const envBookingServiceSpy = jasmine.createSpyObj('EnvironmentBookingService', {
    getBookedEnv: of({/* mock environmentBookingsData here */})
  });


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      providers: [
        { provide: EnvironmentBookingService, useValue: envBookingServiceSpy },
      ]
    })
    .compileComponents();
  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  }));

  it('should call getBookedEnv service ', function () {
    const service = TestBed.get(EnvironmentBookingService); // get your service
    // spyOn(service, 'getBookedEnv').and.callThrough(); // create spy
    component.LoadListData('EnvirnmentList');
    expect(service.getBookedEnv).toHaveBeenCalledWith();
  });
});

我希望这有助于您了解如何在方法的订阅中开始测试。