簡體   English   中英

模擬Http獲取單元測試角度服務的請求

[英]Mock Http get request for unit testing angular service

我想知道如何測試具有 http get 和 post 調用的服務功能。 我可以配置規范文件,我可以在其中創建服務實例,也可以關注幾個站點來創建 mockhttp 服務,它說“httpMock.expectOne 不是函數”

從這里參考: https : //alligator.io/angular/testing-http-interceptors/

describe('Service: UserSearchService', () => {

class AppLookupServiceStub {
    //some functions
}

UserSearchService = new UserSearchService(httpMock,
    appLookUpService);

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            HttpClientTestingModule
          ],
    providers: [
        AppHttpService,
        HttpClient,
        AppCookieService,
        CookieService,
        { provide: AppLookupService, useClass: AppLookupServiceStub },
        AppConstants
    ]
    });
});

beforeEach(async() => {
    service = TestBed.get(UserSearchService);
    httpMock = TestBed.get(AppHttpService);

    selectedCriteria = [
        //some data
    ]
    UserSearchOptions = {
        //some data
    }
});

it('should have a service instance', () => {
    expect(service).toBeDefined();
});
it('should make expected calls to getUserSerachOptions', inject(
    [AppHttpService, UserSearchService],
    (
      httpMock: AppHttpService,
      dataService: UserSearchService
    ) => {
    // let spy = spyOn(service, 'getUserSerachOptions');
    // UserSearchService.getUserSerachOptions();
    // expect(spy).toBeDefined();

    dataService.getUserSerachOptions().subscribe(UserSearchOptions => {
        expect(UserSearchOptions).toEqual(UserSearchOptions);
    });

    const req = httpMock.expectOne(`AppConstants.ADMIN_CENTRAL_SELECTION_CRITERIA_URL`);
    expect(req.request.method).toBe("GET");
    req.flush(UserSearchOptions);
}));
it('should get the data successful', () => {
    service.getUsersBySelectionCriteria(selectedCriteria[0]).subscribe((data: any) => {
        console.log(data);
      expect(data.country.name).toBe('Australia');
    });
});

})

服務測試規范:

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);
}

我如何模擬 get 調用,在這種情況下我找不到任何來源。

我認為這是錯誤的

 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
 ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM