如何从组件功能测试角度服务?

时间:2019-11-14 05:04:36

标签: angular jasmine angular-testing

我正在尝试测试组件中发生的网络通话。

我想在测试类中调用ngOnInit函数,该函数调用另一个函数,这些函数随后通过服务函数进行网络调用。

这是我的TestComponent.ts

@Component({
  selector: 'test-cmp',
  templateUrl: './test-cmp.component.html',
  styleUrls: ['./test-cmp.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestComponent implements OnInit, OnChanges {

constructor(private logger: LoggingService, public teststore: TestStore, private cdr: ChangeDetectorRef) {
    this.testProductList = new Array();
    setInterval(() => {
      this.cdr.detectChanges();
    }, 3000);
  }


  ngOnInit() {
    this.init();
  }

  private init() {
      this.getProductListForVault();
  }

  // this functions make network calll

  getProductListForVault() {
    this.teststore.getProductInfoData().subscribe(productInfoData => {
      console.log('got product data', productInfoData);
    });
  }
}

这是我的测试班

describe('TestComponentTest', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let logger: LoggingService;
  let testStore: TestStore;
  let cdr: ChangeDetectorRef;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      imports: [HttpClientTestingModule],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [TestStore]
    })
    .compileComponents();
  }));

it( 'calling onInit should call getsitelogin', inject([HttpTestingController, TestStore],
    (httpMock: HttpTestingController, service: TestStore) =>  {
   spyOn(service, 'getProductInfoData');
   spyOn(component, 'ngOnInit').and.callThrough();
   component.ngOnInit();
   expect(service.getProductInfoData).toHaveBeenCalledTimes(1);
  }));

});

测试失败,显示以下结果

  

预期的间谍getProductInfoData已被调用一次。它是   被称为0次。错误:预期的间谍getProductInfoData已经   打电话一次。被打了0次。

为什么会这样?任何建议都欢迎。

0 个答案:

没有答案