Test Angular2 service with mock backend

stealththeninja

First: I'm aware that Angular2 is in alpha and changing frequently.

I'm working with Angular2. There is an injectable service with http dependency that I'd like to test using a mock backend. The service works when the app starts but I'm having no luck writing the test and getting the mock backend to respond. Any insight, is there something obvious in the test setup or implementation that I'm missing?

service/core.ts:

import { Injectable } from 'angular2/angular2';
import { Http } from 'angular2/http';

@Injectable()
export class CoreService {

    constructor(public http:Http) {}

    getStatus() {
        return this.http.get('/api/status')
            .toRx()
            .map(res => res.json());
    }
}

service/core_spec.ts:

import {
    AsyncTestCompleter,
    TestComponentBuilder,
    By,
    beforeEach,
    ddescribe,
    describe,
    el,
    expect,
    iit,
    inject,
    it,
    xit
} from 'angular2/test';
import { MockBackend, MockConnection, BaseRequestOptions, Http, Response } from 'angular2/http';
import { Injector, bind } from 'angular2/angular2';
import { ObservableWrapper } from 'angular2/src/core/facade/async'

import { CoreService } from 'public/services/core'

export function main() {

    describe('public/services/core', () => {

        let backend: MockBackend;
        let response: Response;
        let coreService: CoreService;
        let injector: Injector;

        afterEach(() => backend.verifyNoPendingRequests());

        it('should get status', inject([AsyncTestCompleter], (async) => {

            injector = Injector.resolveAndCreate([
                BaseRequestOptions,
                MockBackend,
                bind(Http).toFactory((backend, options) => {
                    return new Http(backend, options)
                }, [MockBackend, BaseRequestOptions]),
                bind(CoreService).toFactory((http) => {
                    return new CoreService(http);
                }, [Http])
            ]);

            backend = injector.get(MockBackend);
            coreService = injector.get(CoreService);
            response = new Response('foo');

            ObservableWrapper.subscribe<MockConnection>(backend.connections, c => {
                expect(c.request.url).toBe('/api/status');
                c.mockRespond(response);
            });

            // attempt #1: fails because res argument is undefined
            coreService.getStatus().subscribe(res => {
                expect(res).toBe('');
                async.done();
            });

            // attempt #2: fails because emitter.observer is not a function
            ObservableWrapper.subscribe(coreService.getStatus(), res => {
                expect(res).toBe('');
                async.done();
            });

        }));
    });

}

Related: https://github.com/angular/angular/issues/3502 https://github.com/angular/angular/issues/3530

Wojciech Kwiatek

I just found this topic while looking for testing tips but I can't see a direct answer to that so...

This one is based on Angular RC.1

Testing service with Mock Backend

Let's say your service is:

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

@Injectable()
export class CoreService {
  constructor(private http: Http) {}

  getStatus() {
    return this.http.get('/api/status');
  }
}

Test to the service above will look like this:

import {
  beforeEach,
  beforeEachProviders,
  describe,
  expect,
  inject,
  it,
} from '@angular/core/testing';

import { provide } from '@angular/core';
import { BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

describe('Http', () => {

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

  beforeEach(inject([MockBackend], (backend: MockBackend) => {
    const baseResponse = new Response(new ResponseOptions({ body: 'status' }));
    backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
  }));

  it('should return response when subscribed to getStatus',
    inject([CoreService], (coreService: CoreService) => {
      coreService.getStatus().subscribe((res: Response) => {
        expect(res.text()).toBe('status');
      });
    })
  );

})

What you really have to look at there is to have proper mocking in beforeEachProviders. Test itself is quite simple and ends up with subscribing to the service method.


Note: Don't forget to set base providers first:

import { setBaseTestProviders } from '@angular/core/testing';
import {
  TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS,
  TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
} from '@angular/platform-browser-dynamic/testing';

setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Angular2/testing: how to run test with mock service provider?

From Dev

How to mock Angular $q service in Jasmine test?

From Dev

mock angular service/promise in a karma/jasmine test

From Dev

How to mock Symfony 2 service in a functional test?

From Dev

How to mock AngularFire 2 service in unit test?

From Dev

How to mock AngularFire 2 service in unit test?

From Dev

Test angular2 http service

From Dev

Eclipse Scout Neon mock backend service

From Dev

Angular Test only works with mock service class but not value

From Dev

How to Test Angular2 / TypeScript HTTPService without Mock

From Dev

angular2 test, how do I mock sub component

From Dev

Test is not running service mock promise (.then)

From Dev

Mock a service in E2E test in protractor

From Dev

Mock a service in E2E test in protractor

From Dev

Mock backend for Angular / Gulp app

From Dev

Angular Karma Unit Test: How to inject a mock service in karma configuration instead of in all test specs

From Dev

Angular2 test fail when mocking a service

From Dev

Angular2 Service Unit Test Fails with TypeError: undefined is not an object

From Dev

How to test angular2 class/service with parameters inside constructor?

From Dev

Correct way to mock an AngularJS Service in a unit test?

From Dev

how to mock $window to unit test AngularJS service?

From Dev

AngularJS Controller As Jasmine test with mock service with promise

From Dev

Grails Spock Mock Injected Service in Unit Test

From Dev

mock resttemplate to test a service as restFul client

From Dev

How to mock service and test POST controller method

From Dev

How to test function in AngularJS service with mock data

From Dev

How to mock out call to service in an integration test?

From Dev

Using Angular Mock Backend resource multiple times

From Dev

Listen to changes on mock-service in Angular 2

Related Related

  1. 1

    Angular2/testing: how to run test with mock service provider?

  2. 2

    How to mock Angular $q service in Jasmine test?

  3. 3

    mock angular service/promise in a karma/jasmine test

  4. 4

    How to mock Symfony 2 service in a functional test?

  5. 5

    How to mock AngularFire 2 service in unit test?

  6. 6

    How to mock AngularFire 2 service in unit test?

  7. 7

    Test angular2 http service

  8. 8

    Eclipse Scout Neon mock backend service

  9. 9

    Angular Test only works with mock service class but not value

  10. 10

    How to Test Angular2 / TypeScript HTTPService without Mock

  11. 11

    angular2 test, how do I mock sub component

  12. 12

    Test is not running service mock promise (.then)

  13. 13

    Mock a service in E2E test in protractor

  14. 14

    Mock a service in E2E test in protractor

  15. 15

    Mock backend for Angular / Gulp app

  16. 16

    Angular Karma Unit Test: How to inject a mock service in karma configuration instead of in all test specs

  17. 17

    Angular2 test fail when mocking a service

  18. 18

    Angular2 Service Unit Test Fails with TypeError: undefined is not an object

  19. 19

    How to test angular2 class/service with parameters inside constructor?

  20. 20

    Correct way to mock an AngularJS Service in a unit test?

  21. 21

    how to mock $window to unit test AngularJS service?

  22. 22

    AngularJS Controller As Jasmine test with mock service with promise

  23. 23

    Grails Spock Mock Injected Service in Unit Test

  24. 24

    mock resttemplate to test a service as restFul client

  25. 25

    How to mock service and test POST controller method

  26. 26

    How to test function in AngularJS service with mock data

  27. 27

    How to mock out call to service in an integration test?

  28. 28

    Using Angular Mock Backend resource multiple times

  29. 29

    Listen to changes on mock-service in Angular 2

HotTag

Archive