Home Ask Login Register

Developers Planet

Your answer is one click away!

HomeBrew February 2016

Correct way to test http request URL's in Angular 2

Using Angular 2 I have set up a few services and each method inside returns a different http request, something like this:

public create(user:User): Observable<any> {
  return this.http.post(this._apiUrls.create,
    JSON.stringify(user), {
      headers: this.apiConfig.getApiHeaders()

I want to test this method. I'm testing the request url, the headers, and the user. I'm a bit stuck on the url part, I can test the actual url but I can't figure out how to test if it's a GET, POST etc... In Angular 1 we used something like expectGET or expectPOST. This is how I'm doing it so far:

beforeEachProviders(() => [
  provide(Http, {
    useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
    deps: [MockBackend, BaseRequestOptions]

it('Should make a request to login a new user', inject([Authentication, MockBackend], (service, mockBackend) => {
  let connection;
  connection = mockBackend.connections.subscribe(c => connection = c);
  service.create(setUser()).subscribe((res) => {

Any idea how to get the type of request it is? Or am I just doing it wrong?


MattScarpino February 2016

Instead of calling http.get or http.post, you can call http.request with a Request object. The class API is here. The first member is a value of the RequestMethod enumerated type, so you should be able to test that in Jasmine.

cexbrayat February 2016

There is currently (beta.3) no easy way to test this (like expectGET in AngularJS 1.x), but you are on the right track.

You can do:

service.create(setUser()).subscribe((res) => {

I opened an issue a while ago to have a nicer API for test, you can follow it on Github

Post Status

Asked in February 2016
Viewed 1,282 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life