Angular 单元测试未正确从间谍对象调用 API 服务方法

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

我有以下组件和规范文件,尝试测试命中 API 端点并基于 id 返回字符串的服务调用。根据我传入的

employerId
,我希望返回“注册雇主”并将其设置为
employerName
。该测试总是失败并出现错误
Expected undefined to be 'Enrollment Employer'

我可以调试并查看传递给 getEmployerName() 的正确

employerId
,但我没有收到响应。我正确地编写了这个测试吗?

规格:

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

    employerService = debugElement.injector.get(EmployerService);
    employerSpy = spyOn(employerService, 'getEmployerName').and.callThrough();

    fixture.detectChanges();
  });


  it('should call the employer service and return the employer name', () => {
    component.employerId = 12485;
    component.getEmployerName();
    expect(employerSpy).toHaveBeenCalled();
    expect(component.employerName).toBe('Enrollment Employer');
  })

成分:

  getEmployerName() {
    this.employerService.getEmployerName(this.employerId).subscribe(res => {
      this.employerName = res.empName;
    });
  }

服务:

  getEmployerName(employerId: number) {
    const url = `${this.url}getEmployerName?employerId=${employerId}`
    return this.apiService.request<any>({ url, method: HttpReqMethod.GET })
  }
angular jasmine
1个回答
0
投票

您可以使用

fakeAsync
flush
等待API调用。

it('should call the employer service and return the employer name', fakeAsync(() => {
    component.employerId = 12485;
    component.getEmployerName();
    flush();
    expect(employerSpy).toHaveBeenCalled();
    expect(component.employerName).toBe('Enrollment Employer');
}));

您还可以伪造 API 调用以节省时间!

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

    employerService = debugElement.injector.get(EmployerService);
    employerSpy = spyOn(employerService, 'getEmployerName').and.returnValue(of({empName: 'test'}));

    fixture.detectChanges();
  });


  it('should call the employer service and return the employer name', fakeAsync(() => {
      component.employerId = 12485;
      component.getEmployerName();
      flush();
      expect(employerSpy).toHaveBeenCalled();
      expect(component.employerName).toBe('Enrollment Employer');
  }));
© www.soinside.com 2019 - 2024. All rights reserved.