我正在尝试将模拟JSON数据传递给我的jasmine单元测试。
我的JSON格式与下面的格式类似
Array.prototype.choice = function(){
return this[~~(Math.random()*this.length)];
};
// now you can call it like this :)
console.log( ["0", "911"].choice() );
我使用上面的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"
}
]
}
}
}
}
我面临的问题是,我无法将CompanyResponse作为一个整体传递给getTotal()函数,即使我执行JSON.stringify()也无法工作 - 因为它只是将它转换为字符串,如果我执行JSON.parse(),它将无效,因为它将它转换回Object格式。
请提供相同的观点。
下面列出了我们如何在正常场景中调用getTotal()方法
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());
}
干杯, 大师
答案 0 :(得分:2)
您可以使用standard Response Interface from the JavaScript Fetch API来模拟响应对象吗?
如果查看documentation for the constructor method,则会接受body
参数和init
选项对象。 body
参数可以是Blob,因此您可以;
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);
这将创建一个Response
对象,您应该能够将其传递给测试。