gpt4 book ai didi

unit-testing - 带有可观察对象的单元测试模拟服务 => 订阅不是函数

转载 作者:太空狗 更新时间:2023-10-29 17:50:18 24 4
gpt4 key购买 nike

我正在尝试为我用 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}

我希望你们能再帮我一次。

最佳答案

您应该使用 Observable.of 而不是 Observable.create,因为您想要创建一个 RestData 流。

"Converts arguments to an observable sequence"

同时创建

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

阅读更多关于 of 的信息和 create .

关于unit-testing - 带有可观察对象的单元测试模拟服务 => 订阅不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41845515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com