组件是否调用Http服务方法进行角单元测试:错误: :找不到要监视的对象

问题描述 投票:1回答:1

我的目的是测试组件方法是否调用服务方法。服务方法实现是Post,但是我对post机制不感兴趣,因为我打算在服务中对其进行测试,而我只是想知道是否调用了正确的服务方法。

我是单元测试的新手,但是错误指示spyon的用法如下用法spyOn('object,methodName'),指示我没有正确创建要测试的服务对象的实例,但是为了创建服务对象,它在构造函数中需要HttpClient,我已经尝试了很多解决方案,并且我已经阅读了数小时,非常感谢您。

最好,SC

单元测试

describe('SchedulerComponent', () => {
  let component : SchedulerComponent;
  let fixture : ComponentFixture<SchedulerComponent>;
  let schedulerReportService : SchedulerReportService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SchedulerComponent ],
      imports: [BrowserAnimationsModule,
                MatSlideToggleModule,
                MatRadioModule,
                MatFormFieldModule,
                MatInputModule,
                MatSelectModule,
                MatNativeDateModule,
                MatDatepickerModule,
                NativeDateModule,
                NgxMaterialTimepickerModule,
                ReactiveFormsModule,
                FormsModule,
                HttpClientTestingModule],
      schemas:[CUSTOM_ELEMENTS_SCHEMA],
      providers: [{provide : SchedulerReportService}]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SchedulerComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });

  fit('onSubmit should call scheduleReportService',inject([SchedulerReportService], (service: SchedulerReportService) => {

    let scheduleServiceSpy = spyOn(schedulerReportService, 'submitScheduledReport') ;
    let submitReportSpy = spyOn(component, 'onSubmit'); 

    submitReportSpy.and.callThrough();

    expect(scheduleServiceSpy).toHaveBeenCalled();


  }))

相应的服务代码如下

@Injectable({
  providedIn: 'root'
})
export class SchedulerReportService {

  constructor(private http: HttpClient) { }

   submitScheduledReport(servicerequest: ScheduleService) {

    console.log(servicerequest)

    // const headers = new HttpHeaders({'key':'value'});
    // return this.http.post<ScheduleService>(localUrl, servicerequest, {headers : headers} ).pipe(
    //   retry(1), catchError(this.handleError<ScheduleService>('scheduled report post error')));

  }

该组件包含触发服务的方法

export class SchedulerComponent implements OnInit {

  constructor(private fb: FormBuilder,
              private schedulerReportService: SchedulerReportService) { 
    onSubmit(){

    let report = this.schedulerForm.value;
    let scheduleServiceModel = new ScheduleService(report)
    this.schedulerReportService.submitScheduledReport(scheduleServiceModel);

  }
}
angular unit-testing jasmine karma-jasmine
1个回答
1
投票

为了特别解决上面代码中的问题,您需要在调用spyOn之前设置服务实例。像这样的东西:

 schedulerReportService = fixture.debugElement.injector.get(SchedulerReportService);

  ...

 let scheduleServiceSpy = spyOn(schedulerReportService, submitScheduledReport');

但是我推荐使用服务间谍程序存根的另一种方法。由于您不需要测试服务,因此只需要调用服务方法即可,无需注入原始的SchedulerReportService即可,您可以像这样向Angular提供服务对象间谍:

describe('SchedulerComponent', () => {
  let component : SchedulerComponent;
  let fixture : ComponentFixture<SchedulerComponent>;
  let schedulerReportService = jasmine.createSpyObj('SchedulerReportService', ['submitScheduledReport']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SchedulerComponent ],
      imports: [BrowserAnimationsModule,
                MatSlideToggleModule,
                MatRadioModule,
                MatFormFieldModule,
                MatInputModule,
                MatSelectModule,
                MatNativeDateModule,
                MatDatepickerModule,
                NativeDateModule,
                NgxMaterialTimepickerModule,
                ReactiveFormsModule,
                FormsModule,
                HttpClientTestingModule],
      schemas:[CUSTOM_ELEMENTS_SCHEMA],
      providers: [{provide : SchedulerReportService, useValue: schedulerReportService}]
    })
    .compileComponents();

    fixture = TestBed.createComponent(SchedulerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('onSubmit should call scheduleReportService', () => {
    component.onSubmit();
    expect(schedulerReportService.submitScheduledReport).toHaveBeenCalled();
  }));

通过这种方式,您可以测试是否调用了schedulerReportService.submitScheduledReport,而没有原始服务http调用的开销。

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