我试图为在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<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;
}
}
这是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}
我希望你们能再帮助我一次。