1

I'm testing an angular 4 service with a dependency on the Http service. The testing guide suggests using isolated unit tests where the service instance is created with the new keyword:

beforeEach(() => { service = new FancyService(); });

But when FancyService uses the Http service, I get the error

Supplied parameters do not match any signature of call target.

This makes sense as the Http service is in the FancyService constructor. So I add a new Http instance as below, but I get the same error.

beforeEach(() => { service = new FancyService(new Http())})

How can I make my service available in the tests?

2
  • Did you import HttpModule in your testing module? Also I suggest using injection in particular tests(so no new FancyService()) Commented Aug 24, 2017 at 14:58
  • No, I've tried to keep it the same as the example in the link. The only difference is that now FancyService has a function returning http.get(.... So in the test I've just imported Http from @angular/http and plugged it in as above. Commented Aug 24, 2017 at 15:03

1 Answer 1

1

You need to mock the dependency - use a stub service with nessesary methods.

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/take';

class FancyService {
  constructor(private http: HttpClient) {}

  getFancy(): Observable<any> {
    return this.http.get('url');
  }
}

describe('FancyService', () => {
  let service: FancyService;

  it('can get fancy', () => {
    const fakeHttpClient = {
      get: () => {}
    };
    spyOn(fakeHttpClient, 'get').and.returnValue(Observable.of('data'));

    service = new FancyService(<any>fakeHttpClient);

    service.getFancy().take(1).subscribe(
      (result: any) => {
        expect(result).toBe('data');
      }
    );
    expect(fakeHttpClient.get).toHaveBeenCalledTimes(1);
    expect(fakeHttpClient.get).toHaveBeenCalledWith('url');
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

How would I do that for isolated tests?
Thanks, but I'm getting the following error when setting service = new FancyService(... Type '{ get: () => void; }' cannot be converted to type 'HttpClient'. Property 'handler' is missing in type '{ get: () => void; }'
Use service = new FancyService(<any>fakeHttpClient); instead

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.