1

I want to know how I can test my service function that has a http get and post calls. I could configure the spec file where I could create an instance of the service, also followed few sites for creating a mockhttp service, It says "httpMock.expectOne is not a function"

reference from here: 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');
    });
});

})

test spec for service:

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

How do I mock the get call, I am unable to find any sources in this case.

1 Answer 1

1

i think that this is wrong

 httpMock = TestBed.get(AppHttpService);

it should be

 httpMock = TestBed.get(HttpTestingController);

httpMock is an HttpTestingController, try this

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

your test

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

 httpMock.expectOne(...)  // this should work now
 ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Replacing "AppHttpService" with "HttpTestingController" breaks all others test files as well, and returns this message. Error: StaticInjectorError(DynamicTestModule)[EmployeeRecordFormService -> AppHttpService]: StaticInjectorError(Platform: core)[EmployeeRecordFormService -> AppHttpService]: NullInjectorError: No provider for AppHttpService!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.