我正在尝试为用Typescript / Angular2编写的模拟服务设置一些单元测试。当我尝试在单元测试中从服务调用任何方法时,我得到
TypeError: this._subscribe is not a function
在正常使用中,该服务运行良好。
我的虚拟服务如下所示:
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{ 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; } }
这是RestData:
export interface RestData { id?: number; usable?: boolean; someValue?: string; otherValue?: string; }
以及失败的单元测试:
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(); }); })); })
我尝试了多种方法来设置测试,但没有一种有效。我也在互联网上进行了很多搜索,但找不到任何遇到相同问题的人。奇怪的是,服务已定义,当我这样做时
console.log(JSON.stringify(service.getDummyData()));
我得到:
Observable {_isScalar: false, _subscribe: Object}
希望你们能再帮我一次。
您应使用Observable.of
而不是Observable.create
来创建的流RestData
。of
“将参数转换为可观察的序列”
而 create
“通过函数从头创建一个Observable”
详细了解of和create。