简体   繁体   中英

Unit test mock service with observables => Subscribe is not a function

I'm trying to set up some unit test for my mock services written in Typescript/Angular2. When I try to call any method from the service in my unit test I get

TypeError: this._subscribe is not a function

In normal use the service works fine.

My dummy service looks like this:

    import {Observable} from 'rxjs/Rx';
import {Zahlungsverbindung, ZahlungsverbindungArtEnum} from '../../model/zahlungsverbindung.model';
import {Response} from '@angular/http';
import {RestData} from '../RestData';
import {Injectable} from '@angular/core';

@Injectable()
export class DummyDataServiceMock {

  private _someData : RestData = this.createDummyData();


  public getDummyData(): Observable<RestData> {
    return Observable.create(this._someData);
  }

  private createDummyData(): RestData {

    let id = 1;

    let usable = true;
    let someValue = 'AKTUELL';
    let otherValue = 'Dummy Person';

    let restData: RestData = {
      id: id,
      usable: usable,
      someValue: someValue,
      otherValue: otherValue,

    }

    return restData;
  }

}

Here is the RestData:

export interface RestData {
  id?: number;
  usable?: boolean;
  someValue?: string;
  otherValue?: string;
}

And the failing unit test:

import {DummyDataServiceMock} from '../DummyData.service.mock.ts';
import {RestData} from '../RestData.ts';
import {TestBed, inject, async} from '@angular/core/testing';


describe('DummyService (Mocked)', () => {

  let service;


  beforeEach(() => TestBed.configureTestingModule({
    providers: [DummyDataServiceMock],
  }));

  beforeEach(inject([DummyDataServiceMock], s => {
    service = s;

  }));

  it('Service should be defined', async(() => {

    expect(service).toBeDefined();


  }));

  it('Get dummy data from service', async(() => {

    let restData: RestData;

    service.getDummyData().subscribe(data => {
      restData = data
      expect(restData.id).toBeDefined();
    });


  }));
})

I tried many ways to set up the test, but none of them worked. I also searched much in the internet but i could not find anyone with the same problem. The strange thing is that the service is defined, and when I do

console.log(JSON.stringify(service.getDummyData()));

I get:

Observable {_isScalar: false, _subscribe: Object}

I hope you guys can help me out one more time.

You should use Observable.of instead of Observable.create as you want to create a stream of RestData . of

"Converts arguments to an observable sequence"

while create

"creates an Observable from scratch by means of a function"

Read more about of and create .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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