3

I have this service I need to test:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class LoginService {

  private baseUrl: string = 'http://localhost:4000/';

  constructor (private http: Http) {}

  public getBaseUrl() {
    return this.baseUrl;
  }

  getLogin() {
    return this.http.get(this.baseUrl + 'api/auth/octopus')
      .map(res => res.json().redirect);
  }
}

To test the getLogin() function I have this code:

import {
  async,
  describe,
  it,
  expect,
  beforeEach,
  addProviders,
  inject
} from '@angular/core/testing';
import { provide} from '@angular/core';
import { LoginService } from './login.service';
import {
  Http,
  BaseRequestOptions,
} from '@angular/http';
import {MockBackend} from '@angular/http/testing';


describe('Service: LoginService', () => {

  beforeEach(() => addProviders([
    LoginService,
    BaseRequestOptions,
    MockBackend,
    provide(Http, {
      useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
        return new Http(backend, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions]
    })
  ]));

  it('should return data.',
    async(inject([LoginService], (loginService: LoginService) => {
      loginService.getLogin().subscribe(
        data => console.log(data)
      );
    })
  ));

});

However, the data doesn't get logged. I tried various solutions that I found on SO or on the internet.

One of them was to make a http call to the mockbackend but that just gave me data = undefined.

1 Answer 1

3

You need to inject MockBackend and subscribe for connection, like this:

UPDATE

async(inject([LoginService, MockBackend], (loginService: LoginService, mockBackend:MockBackend) => {
  let mockResponse = new Response(new ResponseOptions({body: {'redirect': 'some string'}}))
  mockBackend.connections.subscribe(c => c.mockRespond(mockResponse));
  loginService.getLogin().subscribe(
    data => console.log(data)
  );
})

For more details go here:

https://angular.io/docs/ts/latest/api/http/testing/index/MockBackend-class.html

Sign up to request clarification or add additional context in comments.

2 Comments

this gives me: Unexpected token y in JSON at position 0
ok, just change 'youData' string to a json, smth like that: {'redirect': 'some string'}

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.