0

I am trying to unit test a function that is subscribed to an observable service. Not sure where to start.

Component function I am trying to unit test:

  register() {
    this._registrationService.registerUser(this.form.value)
        .subscribe(data => {
          if (data) {
            this.errorMessage = '';
            this.successMessage = 'Account successfully created';
          } else {
            this.errorMessage = 'Error';
            this.successMessage = '';
          }
        },
        error => {
          this.errorMessage = error;
          this.successMessage = '';
        });
  }

Service:

  registerUser(user) {
    const registerUrl = this.apiUrl;

    return this._http.post(registerUrl, JSON.stringify(user), { headers: this.apiHeaders })
      .map(res => res.json())
      .catch(this._handleError);
  }

3 Answers 3

1

I would mock the RegistrationService service to return data using Observable.of.

class MockRegistrationService {
  registerUser(data: any) {
    return Observable.of({});
  }
}

Within you unit test, you need to override the RegistrationService service by the mocked one:

describe('component tests', () => {
  setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS,
                   TEST_BROWSER_APPLICATION_PROVIDERS);

  var service = new MockRegistrationService();

  beforeEachProviders(() => [
    provide(RegistrationService, { useValue: service })
  ]);

  it('should open', 
    injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
      return tcb
      .createAsync(RegistrationComponent)
      .then(fixture => {
        let elt = fixture.nativeElement;
        let comp: RegistrationComponent = fixture.componentInstance;

        fixture.detectChanges();

        expect(comp.successMessage).toEqual('Account successfully created');
        expect(comp.errorMessage).toEqual('');
      });
    });
  }));
});

See this plunkr for more details: https://plnkr.co/edit/zTy3Ou?p=info.

0

In the unit test there is only one "real" object: the one you're testing. Dependencies, like other objects and functions, should be mocked.

Mocking is creating objects that simulate the behaviour of real objects. This topic contains more information: What is Mocking?

I am not familiar wih Jasmine, but here I found an article that could be useful: https://volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine

0

Posting my working test/spec file if anyone is wondering how this turned out:

Test File:

import {
  it,
  inject,
  injectAsync,
  describe,
  beforeEachProviders,
  TestComponentBuilder,
  resetBaseTestProviders,
  setBaseTestProviders
} from 'angular2/testing';

import {TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS} from 'angular2/platform/testing/browser';
import {Observable} from 'rxjs/Rx';
import {provide} from 'angular2/core';
import {RootRouter} from 'angular2/src/router/router';
import {Location, Router, RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';
import {SpyLocation} from 'angular2/src/mock/location_mock';

import {RegistrationService} from '../shared/services/registration';
import {Register} from './register';
import {App} from '../app';

class MockRegistrationService {
  registerUser(user) {
    return Observable.of({
      username: 'TestUser1',
      password: 'TestPassword1'
    });
  }
}

describe('Register', () => {
  resetBaseTestProviders();
  setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS);

  let registrationService = new MockRegistrationService();

  beforeEachProviders(() => [
    Register,
    RouteRegistry,
    provide(RegistrationService, { useValue: registrationService }),
    provide(Location, {useClass: SpyLocation}),
    provide(Router, {useClass: RootRouter}),
    provide(ROUTER_PRIMARY_COMPONENT, {useValue: App})
  ]);


  it('should open', injectAsync([TestComponentBuilder], (tcb) => {
      return tcb
        .createAsync(Register)
        .then(fixture => {
          let registerComponent = fixture.componentInstance;

          fixture.detectChanges();

          registerComponent.register({
            username: 'TestUser1',
            password: 'TestPassword1'
          });

          expect(registerComponent.successMessage).toEqual('Account successfully created');
          expect(registerComponent.errorMessage).toEqual('');
        });
    }));

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.