【发布时间】:2017-10-17 16:21:09
【问题描述】:
我正在尝试将模拟 JSON 数据传递到我的 jasmine 单元测试中。
我的 JSON 格式如下:
{
"CompanyResponse":{
"CompanyCreatedDate":"1990-10-02",
"RunDate":"2",
"LastChangedDate":"2015-10-02",
"CompanySummary": {
"Id":"Apple",
"MaximumCredit":"10000000",
"Margin":"60000000",
"Limit":"-1500000",
"HistoricData":{
"CompanyHistoricData": [
{
"LaunchDate":"2008-08-31",
"Product":"Iphone2",
"TotalProductsCreated":"1000000",
"TotalProductsSold":"800000",
"TotalReturns":"200000",
"TotalMargin":"600000"
},
{
"LaunchDate":"2010-08-31",
"Product":"Iphone4",
"TotalProductsCreated":"2000000",
"TotalProductsSold":"1500000",
"TotalReturns":"350000",
"TotalMargin":"800000"
}
]
},
"RefurbishedData": {
"CompanyRefurbished": [
{
"Id":"Apple.201221.12",
"ProductId":"iph-213454",
"StartDate":"2015-09-07",
"FinishDate":"2015-09-10",
"CostOfRefurbishing":"50"
},
{
"Id":"Apple.201228.12",
"ProductId":"iph-4155655",
"StartDate":"2015-09-10",
"FinishDate":"2015-09-12",
"CostOfRefurbishing":"85"
}
]
}
}
}
}
我正在使用上面的 JSON 传递给类似于下面的函数进行单元测试:
public getTotal(response: CompanyResponse): void {
var companySummary = response.CompanySummary;
//gets total 'CostOfRefurbishing' for all phones
var totalRefurbishmentAmount :number = 0;
for (let companyRefurbishments of companySummary.RefurbishedData) {
totalRefurbishmentAmount += Number.parseInt(companyRefurbishments.CostOfRefurbishing.toString());
}
}
我面临的问题是我无法将CompanyResponse 作为一个整体传递给getTotal() 函数。即使我使用JSON.stringify(),它也不起作用,因为它只是将其转换为字符串,如果我使用JSON.parse(),它也不起作用,因为它将它转换回对象格式。
下面是我们在正常情况下如何调用getTotal() 方法:
export class MyService{
async CompanySummary(): Promise<CompanySummaryResponse>
{
const response = await this.http.fetch('CompanySummary');
return await response.json();
}
}
var myService = new MyService();
CompanySummary: CompanySummaryResponse;
CompanySummary = await myService.CompanySummary();
this.calculator.getTotal(CompanySummary);
干杯, 大师
【问题讨论】:
-
Reallocations在您的数据中的什么位置? -
您需要
CompanyResponse有一个构造函数,该构造函数将该对象或从该对象派生的东西作为参数 -
@torazaburo 对不起我的错。它在 JSON 中的 RefurbishedData,而不是重新分配
-
@arboreal84 ,这是单元测试的一部分,我试图不重组我的程序以使单元测试工作。在实际场景中,它是一个 HTTP 调用,它给了我真正的响应 JSON。
标签: javascript json jasmine aurelia