Post

Angular 2 MockBackend Service Testing Template Using TestBed

Below is a template for using TestBed and MockBackend for mocking Angular 2 HTTP calls.

If you want to make actual wire calls, see Angular 2 Services Testing Template instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { async, inject, TestBed } from '@angular/core/testing';
import { BaseRequestOptions, Http, HttpModule, Response, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';

import { SomeService } from './some.service';

describe('SomeService (Mocked)', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        SomeService,

        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend, options) => new Http(backend, options),
          deps: [MockBackend, BaseRequestOptions]
        }
      ],
      imports: [
        HttpModule
      ]
    });
  });

  it('should construct', async(inject(
    [SomeService, MockBackend], (service, mockBackend) => {

    expect(service).toBeDefined();
  })));

  describe('someMethod', () => {
    const mockResponse = {
      color: 'blue'
    };

    it('should parse response', async(inject(
      [SomeService, MockBackend], (service, mockBackend) => {

      mockBackend.connections.subscribe(conn => {
        conn.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(mockResponse) })));
      });

      const result = service.someMethod();

      result.subscribe(res => {
        expect(res).toEqual({
          color: 'blue'
        });
      });
    })));
  });
});

For a working example see https://github.com/kendaleiv/angular-testing/blob/master/src/app/stock-retriever.service.spec.ts.

If you’re interested, check out Angular 2 Component Testing Template Using TestBed.

This post is licensed under CC BY 4.0 by the author.