简体   繁体   English

Angular 2单元测试使用Observable和Redux Rxjs选择器的服务

[英]Angular 2 Unit Testing a service that uses a Observable and Redux Rxjs selector

I am trying to setup a Karma Jasmine Unit test for a Angular 2 service. 我正在尝试为Angular 2服务设置Karma茉莉花单元测试。 The service is called CreditService . 该服务称为CreditService The service has a observable property _credit$ and implements a ng2-redux selector @select(s => s.credit) to get the credit object from a Redux store. 该服务具有可观察到的属性_credit $,并实现了ng2-redux选择器@select(s => s.credit)以从Redux存储获取信用对象。

import {Injectable, Inject} from '@angular/core';
import {ICreditData, ICreditSubmissionData, ContractType, ICredit} from '../../store/type-store/credit.types';
import 'rxjs/add/operator/map';
import {AppStateService} from '../app-state-service/app-state-service';
import {select} from 'ng2-redux';
import {Observable} from 'rxjs';
import {PromiseService} from '../promise/promise-service';


export interface ICreditResponse {
  errors?: string[];
  token?: string;
  response?: ICreditData;
  submission?: ICreditSubmissionData;
}

export interface ICreditLead {
  address: string;
  aptSuite: string;
  city: string;
  state: string;
  zipCode: number;
  email: string;
  monthlyIncome: number;
  birthDate: string;
  socialSec: number;
  contactPolicy: boolean;
}

@Injectable()
export class CreditService {

  @select(s => s.credit)
  private _credit$: Observable<ICredit>;
  public isPostGA2: boolean = false;

  constructor(@Inject(AppStateService) private _appStateService: AppStateService,
              @Inject(PromiseService) private _promiseService: PromiseService) {
    this.setupSubscriptionForPostGA2();
  }
  /**
   * Method will setup subscription to determine of credit has been
   * pulled or credit has already been pulled and exists in the Redux store.
   */
  public setupSubscriptionForPostGA2(): void {
    // subscribe to the store check for isPostGA2
    this._credit$.subscribe(
      credit => {
        let creditDataExists = (credit.data !== undefined) || credit.data !== null;
        let creditLeadIDExists = (credit.data.LeadID !== undefined) || credit.data.LeadID !== null;
        let creditHistoryExists = (creditDataExists && creditLeadIDExists);
        this.isPostGA2 = (credit.loadComplete || creditHistoryExists);
      },
      err => {}
    );
  }


}

The unit test is pretty basic at this point. 在这一点上,单元测试是非常基本的。 I check to see if the CreditService is defined. 我检查是否已定义CreditService。 My unit test looks as follows: 我的单元测试如下:

import { fakeAsync, inject, TestBed } from '@angular/core/testing';
import { DtmAppModule } from '../../modules/app.module';
import { configureTests } from '../../tests.configure';
import { CreditService } from './credit-service';
import {MockAppStateService} from '../../mock/service/app-state-service-mock';
import {MockPromiseService} from '../../mock/service/promise-service-mock';
import { AppStateService } from '../../services/app-state-service/app-state-service';
import { PromiseService } from '../../services/promise/promise-service';
import {NgRedux} from 'ng2-redux';


describe('Service: Credit', () => {
  let creditService: CreditService = null;

  beforeEach(done => {
    const configure = (testBed: TestBed) => {
      testBed.configureTestingModule({
        imports: [DtmAppModule],
        providers: [
          { provide: AppStateService, useClass: MockAppStateService },
          { provide: PromiseService, useClass: MockPromiseService },
          { provide: NgRedux, useClass: NgRedux },
        ]
      });
    };

    configureTests(configure).then(testBed => {
      done();
    });
  });

  // Inject the service
  beforeEach(inject([CreditService], (service: CreditService) => {
    creditService = service;
  }));

  //Do a simple test
  it('should have a defined service', () => {
    expect(creditService).toBeDefined(false);
  });
});

I am getting a exception when executing the test (see below). 执行测试时出现异常(请参阅下文)。 I believe the exception is because I am trying to preform a 'select' method on a undefined Redux store object. 我认为例外是因为我试图在未定义的Redux存储对象上执行'select'方法。

  • How do I fix the basic ' toBeDefined ' test? 如何修复基本的“ toBeDefined ”测试?
  • How can I inject Rxjs mock store for testing purposes? 如何为测试目的注入Rxjs模拟存储?
  • Is there a way to mock the return from the _credit$ Observable ? 有没有办法模拟_credit $ Observable的收益?

I am getting a exception when executing the test (see below). 执行测试时出现异常(请参阅下文)。 I believe the exception is the 'select' of a undefined Redux store. 我相信例外是未定义的Redux存储的“选择”。

TypeError: Cannot read property 'select' of undefined
        at CreditService.getter [as _credit$] (webpack:///~/ng2-redux/lib/decorators/select.js:23:0 <- src/tests.entry.ts:150235:47)
        at CreditService.setupSubscriptionForPostGA2 (webpack:///src/services/credit/credit-service.ts:47:17 <- src/tests.entry.ts:24169:17)
        at new CreditService (webpack:///src/services/credit/credit-service.ts:40:2 <- src/tests.entry.ts:24155:14)
        at DynamicTestModuleInjector.get (DynamicTestModule.ngfactory.js:367:71)
        at DynamicTestModuleInjector.getInternal (DynamicTestModule.ngfactory.js:638:53)
        at DynamicTestModuleInjector.NgModuleInjector.get (webpack:///~/@angular/core/src/linker/ng_module_factory.js:94:0 <- src/tests.entry.ts:91283:27)
        at TestBed.get (webpack:///~/@angular/core/bundles/core-testing.umd.js:1114:0 <- src/tests.entry.ts:9003:51)
        at webpack:///~/@angular/core/bundles/core-testing.umd.js:1120:50 <- src/tests.entry.ts:9009:65
        at Array.map (native)
        at TestBed.execute (webpack:///~/@angular/core/bundles/core-testing.umd.js:1120:0 <- src/tests.entry.ts:9009:33)

You can provide an empty mock class to overwrite select: 您可以提供一个空的模拟类来覆盖选择:

export class MockSelect {
}

and then add it to your list of providers: 然后将其添加到您的提供商列表中:

{provide: select, useClass: MockSelect}

You can mock out observables in the same way: 您可以用相同的方式模拟可观察对象:

export class MockObservable<T> {
}

Then just set the values yourself according to what you need in your unit test. 然后,只需根据单元测试中的需要自己设置值即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM