如何在Angular 2 Test中从服务模拟服务

时间:2017-01-24 01:47:14

标签: angular karma-jasmine

我正在为服务编写测试。它调用另一个名为“SignlarService”的服务。所以我想嘲笑SingnalrService,我不知道如何模拟。

我遇到以下错误:

TypeError: signalr.createHubConnetion is not a function

这是vendorService的.spec文件

import { TestBed, async, inject } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { Observable } from 'rxjs';

import { VendorService } from './game-vendor.service';
import { HttpModule, Http, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { SignalrService } from '../shared/services/signalr.service';
import { Store } from '@ngrx/store';

import { RequestService } from '../shared/services/request-handler.service';
import { AppConfig } from './../app.config';
import { MockStore } from '../shared/helper/mock-store-helper';

  beforeEach(() => {

    TestBed.configureTestingModule({
      providers: [
        { provide: RequestService, useValue: {} },
        { provide: SignalrService, useValue: {} },
        { provide: Store, useClass: MockStore },
        VendorService,
        {
          provide: Http,
          userFactory: (mockBackend: MockBackend, options: BaseRequestOptions) => {
            return new Http(mockBackend, options);
          },
          deps: [ MockBackend, BaseRequestOptions ],
        },
        MockBackend,
        BaseRequestOptions,
        AppConfig,
      ],
    });
 });

  it('should toBeTruthy', inject([VendorService], (service: VendorService) => {
    expect(service).toBeTruthy();
  }));
});

这是vendorService.ts,它调用SignalrService

@Injectable()
export class VendorService {
  VendorServiceUrl: string = `${this.config.baseUrl}v1/Vendors`;
  signalrUrl: string = `${this.config.baseUrl}v1/Vendors/signalr`;
  signalrHubName: string = 'VendorsHub';
  constructor(
    private request: RequestService,
    private config: AppConfig,
    private signalr: SignalrService,
    private store: Store<any>,
  ) {
    signalr.createHubConnetion(this.signalrUrl)
      .createHubProxy(this.signalrHubName)
      .event$
      .map(e =>
        new VendorActions.GetVendorAction())
      .subscribe(store);
  }
}

这是signalrService.ts

import { Injectable, Inject, NgZone } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

export class SignalrWindow {
  $: any;
}

export enum ConnectionState {
  Idle = 0,
  Connecting = 1,
  Connected = 2,
  Reconnecting = 3,
  Disconnected = 4,
}

export class SignalrEvent {
  name: string;
  payload: any;
}

export class HubConnection {
  constructor(
    private zone: NgZone,
    public connection: any,
    public connectionState$: Observable<ConnectionState>,
    public error$: Observable<string>) { }

  createHubProxy(hubName: string): HubProxy {
    const eventSubject = new Subject<SignalrEvent>();
    if (this.connection) {
      const newHub = this.connection.createHubProxy(hubName);
      newHub.on('onEvent', (event: SignalrEvent) => {
        this.zone.run(() => eventSubject.next(event));
      });
    }
    return new HubProxy(eventSubject.asObservable());

  }
}

export class HubProxy {
  constructor(public event$: Observable<SignalrEvent>) { }
}

@Injectable()
export class SignalrService {
  constructor(
    @Inject(SignalrWindow) private window: SignalrWindow,
    private zone: NgZone,
  ) { }

  createHubConnetion(url: string): HubConnection {
    const connectionStateSubject = new Subject<ConnectionState>();
    const errorSubject = new Subject<any>();
    if (this.window.$ === undefined || this.window.$.hubConnection === undefined) {
      console.warn('SignalR failed to load. Some features have been disabled.');
      return new HubConnection(this.zone, null, connectionStateSubject.asObservable(), errorSubject.asObservable());
    }
    const connection = this.window.$.hubConnection();
    connection.url = url;

    connection.stateChanged((state: any) => {
      let newState: ConnectionState;
      switch (state.newState) {
        case this.window.$.signalR.connectionState.connecting:
          newState = ConnectionState.Connecting;
          break;
        case this.window.$.signalR.connectionState.connected:
          newState = ConnectionState.Connected;
          break;
        case this.window.$.signalR.connectionState.reconnecting:
          newState = ConnectionState.Reconnecting;
          break;
        case this.window.$.signalR.connectionState.disconnected:
          newState = ConnectionState.Disconnected;
          break;
        default:
          newState = ConnectionState.Idle;
      }
      this.zone.run(() => connectionStateSubject.next(newState));
    });

    connection.error((error: any) => {
      this.zone.run(() => errorSubject.next(error));
    });
    connection.start();
    return new HubConnection(this.zone, connection, connectionStateSubject.asObservable(), errorSubject.asObservable());
  }
}

0 个答案:

没有答案
相关问题