例如网络中有这么一个接口,
apps.service.ts
组件中使用。
test.component.ts
接下来就是要在 spec.ts文件中测试给它。
test.component.spec.ts
创建测试类 并声明他。
const mockHackers = {
editApp:{"note":"SSL_Test5"},
getApps:{count:6,
results:[
{"id":22,"name":"SSL_Test5","sub_tag":"SSL_Test5","ch_type":"04","note":"SSL_Test5","api_id":"8bcc5cc0160545862a9f17d36a98c50ca20b12b9","api_key":"5*wt9=503aonjf))%=q1","created_at":"2022-12-08T13:58:25.502301+08:00"},
{"id":21,"name":"SSL_Test4","sub_tag":"SSL_Test4","ch_type":"03","note":"SSL_Test4","api_id":"45894c7a0c777f4b61b3daf436ed48160268154f","api_key":"z&j_n595yus3_d%f-$q6","created_at":"2022-12-08T13:58:12.449877+08:00"},
]
},
};
class AppServiceSpy {
//测试数据
//模拟接口返回的测试数据,mockHackers的定义在下面
testSourceData: any = mockHackers.getApps;
getApps = jasmine.createSpy("getApps").and.callFake(
() => {
console.log("测试 getApps 走进来没有");
return of(this.testSourceData);
}
)
}
//声明
//单纯用来判断接口被请求了几次,在某些场合很有用.
//使用方式 hdsSpy.getApps.calls.count()
let hdsSpy: AppServiceSpy;
接下来非常重要的一步,重新AppsComponent
组件使用的网络服务
然后就是初始化 hdsSpy
对象
beforeEach(async () => {
hdsSpy = fixture.debugElement.injector.get(AppsService) as any;
})
然后测试网络。
it('should have called `getApps`', () => {
expect(hdsSpy.getApps.calls.count())
.withContext('getApps called once')
.toBe(1, 'getApps called once');
//AppsComponent 组件内部的 dataSource 数量 应该和 mockHackers 中的一致。
expect(component.dataSource.length).toBe(2);
});