Angular 8 Jasmine not matching HTTP request

161 views Asked by At

I have an Angular service making some HTTP requests, and I want to test that it's making them the right way.

Among its dependencies, it also has an EnvironmentService that returns the correct API endpoints according to the environment, that I have mocked with Jasmine.

My test looks like this:

describe('ShipmentsService', () => {

    let httpTestingController: HttpTestingController;
    let service: ShipmentsService;
    const envSpy = jasmine.createSpyObj('EnvironmentService', ['getRestEndpoint', 'dev']);

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                ShipmentsService,
                {provide: EnvironmentService, useValue: envSpy}
            ],
            imports: [HttpClientTestingModule]
        });

        httpTestingController = TestBed.get(HttpTestingController);
        service = TestBed.get(ShipmentsService);
    });

    it('does the right HTTP request', () => {
        envSpy.getRestEndpoint.and.returnValue('foo');
        service.doStuff(123);
        expect(envSpy.getRestEndpoint)
            .toHaveBeenCalledWith('changePackingProperties');

        const request = httpTestingController.expectOne('foo');
        request.flush({shipmentId: 123});
        httpTestingController.verify();    
    });
});

And here is my ShipmentsService method:

doStuff(shipmentId: number) {
    let path = this.environmentService.getRestEndpoint('changePackingProperties');
    return this.http.post(path, body, {headers}).pipe(map(
      (response) => response
    ));
}

What am I missing?

1

There are 1 answers

0
Raibaz On BEST ANSWER

What was missing was that my service method was indeed returning an Observable, so for it to be completed the test needed to be subscribed to it.

TO make the test work, then, the actual service call needed to be

service.doStuff(123).subscribe(() => {});