【发布时间】:2018-10-10 03:12:05
【问题描述】:
我的 Angular 组件中有如下代码部分:
for (const item of items) {
const boxItems = item.boxItems;
if (await self.hasID(boxItems)) {
// perform some logic
}
}
private async hasID(boxItems: BoxItems[]): Promise<boolean> {
for (const item of boxItems) {
let info = (await item.promise).json();
// test fails here, info remains undefined
// how to properly mock a Response object from a Promise at this point?
}
}
因为我使用的是来自here 的.json(),所以我很好奇如何在我的单元测试中模拟它?
我现在正在这样做:
const MockBoxItem = {
promise: new Promise<any>((resolve, reject) => resolve(myData))
};
我是否应该这样做:
const MockBoxItem = {
promise: new Promise<any>((resolve, reject) => resolve(
new Response(new Body([JSON.stringify(myData)]))
)
};
我的单元测试失败,因为我怀疑我返回的模拟数据没有正确实现 Response 对象,因此不包含 .json() 方法。
当我在本地测试此流程时,返回的响应如下所示:
promise: ZoneAwarePromise
_zone_symbol_state: true
_zone_symbol_value: Response
headers: ...
ok: ...
status: ...
statusText: ...
type: ...
url: ...
_body: myData
谢谢
【问题讨论】: