簡體   English   中英

如何對調用可觀察服務的組件進行單元測試

[英]How to unit test a component that calls observable service

我正在嘗試對已訂閱可觀察服務的功能進行單元測試。 不知道從哪里開始。

我正在嘗試對組件功能進行單元測試:

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

服務:

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

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

我將模擬RegistrationService服務以使用Observable.of返回數據。

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

在單元測試中,您需要通過模擬的服務來覆蓋RegistrationService服務:

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

有關更多詳細信息,請參見此plunkr: https ://plnkr.co/edit/zTy3Ou?p = info。

在單元測試中,只有一個“真實”對象:您正在測試的對象。 像其他對象和函數一樣,依賴關系也應該被模擬。

模擬正在創建模擬真實對象行為的對象。 本主題包含更多信息: 什么是模擬?

我對茉莉花不熟悉,但是在這里我發現了一篇可能有用的文章: https : //volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine

如果有人想知道結果如何,請發布我的工作測試/規格文件:

測試文件:

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM