【发布时间】:2021-06-27 04:02:32
【问题描述】:
我还在学习 Jasmine x Karma,当我需要为具有 .subscribe() 的函数创建单元测试时,我陷入了困境 component.ts 中的代码如下所示
loadListDownloadRequestGroup() {
this.noItem = false;
this.listDownloadService.getDownloadRequestGroup(
this.offsetPage,
this.getGroupId,
this.setOrder,
this.keywordSend
).subscribe(resp => {
const getResp: DownloadModel[] = [];
if (resp.items.length) {
resp.items.forEach(item => {
const listArr: DownloadModel = {};
listArr.id = item.id;
listArr.queryId = item.queryId;
listArr.createdAt = item.createdAt;
listArr.filename = item.filename;
listArr.queryName = item.queryName;
listArr.widgetName = item.widgetName;
listArr.type = item.type;
listArr.labelName = item.labelName;
listArr.createdByName = item.createdByName;
listArr.expiredAt = item.expiredAt;
listArr.status = item.status;
listArr.group = item.group;
listArr.groupId = item.group ? item.group.id : null;
listArr.groupName = item.group ? item.group.name : '-';
getResp.push(listArr);
});
} else {
this.noItem = true;
this.emptyDataText = (this.isInitGetlistData == false) ?
'There is no data to display' :
'There is no search result. Please input different keyword';
}
this.dataSourceDT = new MatTableDataSource(getResp);
this.dataSourceDT.sort = this.sort;
this.totalData = resp.total;
this.totalOffset = Math.ceil(this.totalData / 5);
}, (error) => {
if (error.graphQLErrors[0].statusCode === 403) {
this.route.navigate(['unauthorized']);
}
});
}
关于 .spec.ts 我是这样写的,但不会影响代码覆盖率
it('loadListDownloadRequestGroup', () => {
// const getAllDownload = spyOn(listDownloadService, 'getAllDownload').and.callThrough();
const event = { items: [{
id: 2,
queryId: 2,
createdAt: '2019-09-09',
filename: 'test',
queryName: 'test lagi',
widgetName: 'test widget',
type: 'test type',
labelName: 'test labelName',
createdByName: 'test createdByName',
expiredAt: '2019-08-08',
status: 'published',
group: {
id: 1,
name: 'test group'
}
}] };
component.loadListDownloadRequestGroup();
// expect(getAllDownload).toHaveBeenCalled();
expect(component.isInitGetlistData).toBeFalsy();
expect(component.noItem).toBeFalsy();
expect(event.items.length).toEqual(1);
})
【问题讨论】:
标签: angular unit-testing jasmine karma-jasmine