模拟Http获取单元测试角度服务的请求

时间:2019-06-12 09:06:20

标签: angular http testbed

我想知道如何测试具有http get和post调用的服务功能。我可以在配置文件中配置我可以创建服务实例的地方,还可以在几个站点上创建模拟http服务,它说“ httpMock.expectOne不是函数”

引用从这里:https://alligator.io/angular/testing-http-interceptors/

getUserSerachOptions(): Observable<UserSearchOptions> {
if (!this.userSearchCriteriaOptions) {

    return this.appHttpService.get('{apiUrl}/xyzproject/{devKey}/userSelectionCriteria').pipe(map(
      (data: UserSearchOptions) => {
        this.userSearchCriteriaOptions = data;
        return  this.userSearchCriteriaOptions;
      }
    ));
}

return of( this.userSearchCriteriaOptions);
}

服务的测试规格:

"no_i</name><primaryKey>true</primaryKey><newValue>"

我该如何模拟get调用,在这种情况下我找不到任何来源。

1 个答案:

答案 0 :(得分:0)

我认为这是错误的

 httpMock = TestBed.get(AppHttpService);

应该是

 httpMock = TestBed.get(HttpTestingController);

httpMock是 HttpTestingController ,请尝试

import { HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';


describe('Service: UserSearchService', () => {
  let httpMock: HttpTestingController;

 beforeEach(async(() => {
 TestBed.configureTestingModule({
  imports: [
    RouterTestingModule.withRoutes([]),
    HttpClientTestingModule
  ],
  declarations: [Component],
  providers: [

  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
 }).compileComponents();
 fixture = TestBed.createComponent(Component);
 component = fixture.componentInstance;
 httpMock = injector.get(HttpTestingController); // change it here
}));

您的测试

it('should make expected calls to getUserSerachOptions', inject([HttpTestingController],
  (httpTestMock: HttpTestingController) => {

 httpMock.expectOne(...)  // this should work now
 ...
}