角单元测试-未定义组件-“无法读取未定义的'属性'的属性”

时间:2020-06-26 22:23:33

标签: angular unit-testing

.spec

 describe('PageComponent', () => {
  let component: PageComponent;
  let fixture: ComponentFixture<PageComponent>;

  let eventConnectionService: Partial<EventConnectionService>;
  let dataService: Partial<DataService>;
  let deviceService: Partial<DeviceService>;

  beforeEach(async(() => {
    deviceService = {
        get: jasmine.createSpy('get').and.returnValue(of([]))
    };
    // Data service defined here like above 
    // Event service defined here like above

    TestBed.configureTestingModule({
      declarations: [ myDeclarations ],
      imports: [ myModules ],
      providers: [
        { provide: DeviceService, useValue: deviceService},
        { provide: DataService, useValue: dataService },
        { provide: EventConnectionService, useValue: eventConnectionService },
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('Should call service api', () => {
    expect(component.getDevices).toBeTruthy();

    fakeAsync((component) => {
      const getDevicesSpy = spyOn(component, 'getDevices').and.callThrough();
      component.ngOnInit();
      tick();
      expect(getDevicesSpy).toHaveBeenCalled();
    });
  });
});

PageComponent.ts文件

export class PageComponent implements OnInit {
  
  devices: any[];

  constructor(
    private deviceService: DeviceService,
    private dataService: DataService,
    private eventConnectionService: EventConnectionService) {
    }

    ngOnInit() {
      this.getDevices();
  }

  async getDevices() {
    var results = await this.deviceService.get().toPromise();
    this.devices = results 
  }
}

当在测试文件中调用Expect(component.getDevices).toBeTruthy();时,我收到一条错误消息:“无法读取未定义'getDevices'的属性。为什么我的单元测试中的组件未定义?在为服务设置提供程序时缺少某些信息,或者可能与异步有关?

0 个答案:

没有答案