Angular单元测试.subscribe()



无法单元测试subscribe()。

没有返回的结果component.ts

getPortfolioType() {
this.dataService.getPortfolioTypeList()
.subscribe((response: any) => {
this.portfolioType = response.payload.portfolioList;
})
}

data.service.ts

public getPortfolioTypeList(): any {
return this.http.getData('/portfolio/portfolioTypeList');
}

http.service.ts

getData(action: any, data: any = {}): any {
const url = environment.API_URL + action;
const params = Object.keys(data);
let httpParams = new HttpParams();
if (params.length) {
params.forEach((key: string) => {
httpParams = httpParams.append(key, data[key]);
});
}
return this.http.get(url, {params: httpParams});
}

service (pass) Case

it('should pass service getPortfolioTypeList', () => {
const test = {
"test": "test"
}
let result: any;
dataService.getPortfolioTypeList().subscribe(t => {
result = t;
});
const req = httpMock.expectOne({
method: "GET",
url: environment.API_URL + '/portfolio/portfolioTypeList'
});
req.flush([test]);
expect(result[0]).toEqual(test);
});

添加了一个简单的函数调用

it('Get data from getPortfolioType', () => {
component.getPortfolioType();
console.log(component.portfolioType); // <<< is empty
});

组件的原因。portfolioType是否为空?

我找到了一个解决方案

为DataService添加Mock

class MockDataService {
getPortfolioTypeList(): Observable<any> {
return of(
{
"someKey": "someData"
}
)
}
}

和测试用例

it('Check getPortfolioType', fakeAsync(() => {
const testResponse = {
payload: {
portfolioList: [
{
"someKey": "someData1",
}
]
}
};
spyOn(dataService, 'getPortfolioTypeList').and.returnValue(of(testResponse));
fixture.detectChanges();
component.getPortfolioType();
tick();
flush();
fixture.detectChanges();
expect(component.portfolioType).toBe(testResponse.payload.portfolioList);
}));

代码覆盖率

最新更新