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

问题描述 投票:0回答:2

我想进行单元测试并获得所有代码的覆盖,但我无法覆盖订阅中存在的代码我能够监视服务和功能但是在订阅内部我无法进行单元测试并获得代码覆盖率。以下是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;
            }
angular unit-testing observable karma-jasmine subscriber
2个回答
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);
  });

0
投票

您需要模拟服务并让它返回一个Observable。我在StackBlitz中放了一个简单的例子来展示一种用你的代码来解决这个问题的方法。

StackBlitz中需要注意的事项:

  • 我使用spyObject模拟服务,因此以后不需要监视服务。
  • 在这个spyObject中,我将内部函数getBookedEnv()的返回值设置为Observable - 这允许执行subscribe中的代码。
  • 对于任何真正的测试,您应该将getBookedEnv()当前返回的空对象替换为一些合理模拟的数据。
  • 请注意providers数组以及我用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();
  });
});

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

© www.soinside.com 2019 - 2024. All rights reserved.