nav
nav

Reputation: 1

Unit testing http.get call with dynamic response in angular

Is it possible to unit test the http.get calls with actual response and not by mocking the response?

...
export class CarService{
    ...
    getCars():Observable<any>{
        return this.http.get("http://someurl/cars").map( res => res.json() );
    }
    ...
}

Unit test:

it('retrieves all the cars', injectAsync( [CarService], ( carService ) => {
  return carService.getCars().toPromise().then( (result) => {         
     expect(result.length).toBeGreaterThan(0);
  } );       
}) );

It will execute the http.get call and it will pause for few seconds and then it will return the below error:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Upvotes: 0

Views: 181

Answers (2)

nav
nav

Reputation: 1

It's working by adding below snippet inside the beforeEachProviders -

beforeEachProviders(() => {
    window.jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    setTimeout(function () {
        console.log('inside timeout');
    }, 500);

this will remove the time out error and you can test the actual dynamic response coming from API.

Upvotes: 0

victor sosa
victor sosa

Reputation: 899

Dependencies in a unit test should be mocked away. Unit testing, as the name suggests, should test the unit and not its dependencies.

Upvotes: 0

Related Questions