Gur*_*noy 3 javascript json jasmine aurelia
我正在尝试将模拟 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"
}
]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用上面的 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());
}
}
Run Code Online (Sandbox Code Playgroud)
我面临的问题是我无法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);
Run Code Online (Sandbox Code Playgroud)
干杯,大师
您可以使用JavaScript Fetch API 中的标准响应接口来模拟响应对象吗?
如果您查看构造函数方法的文档- 它接受一个body参数和一个init选项对象。该body参数可以是一个斑点,所以你可以;
var data = {foo: "bar"};
var blob = new Blob([JSON.stringify(data, null, 2)], {type : 'application/json'});
var init = { "status" : 200 , "statusText" : "SuperSmashingGreat!" };
var myResponse = new Response(blob, init);
Run Code Online (Sandbox Code Playgroud)
这将创建一个Response您应该能够传递给您的测试的对象。
| 归档时间: |
|
| 查看次数: |
6238 次 |
| 最近记录: |