How to use MockBackend in Angular2

I have this service that I need to check:

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, data is not recorded. I tried various solutions that I found on SO or the Internet.

One of them was to make an http call for mockbackend, but that just gave me data = undefined.

+3
source share
1 answer

You need to enter MockBackend and subscribe to the connection, for example:

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)
  );
})

See here for more details:

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

+3
source

Source: https://habr.com/ru/post/1675099/


All Articles