Converting a JSON object into a response object
Asked Answered
E

1

6

I am trying to pass mock JSON data into my jasmine unit test.

The format of my JSON is like the one below:

{   
   "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"  
               }  
            ]  
         }  
      }  
   }  
}  

I am using the above JSON to pass on to a function similar to the one below for unit testing:

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());
  }
}

The problem I am facing is that I am not able to pass CompanyResponse as a whole to the getTotal() function. It doesn't work even if I use JSON.stringify() because it just converts it to a string and it doesn't work if I use JSON.parse() either as it converts it back into the Object format.

Here's how we call the getTotal() method in a normal scenario:

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);    

Cheers, Guru

Eusebioeusebius answered 18/5, 2017 at 2:51 Comment(4)
Where is Reallocations in your data?Hydrosphere
You need CompanyResponse to have a constructor that takes that object, or something derived from that object, as parameterPestana
@torazaburo sorry my bad. its RefurbishedData in the JSON, not ReallocationsEusebioeusebius
@Pestana , this is a part of unit testing and I am trying not to restructure my program in order to make the unit test work. In the real scenario its an HTTP call that gives me the real response JSON.Eusebioeusebius
H
15

Can you use the standard Response Interface from the JavaScript Fetch API to mock a response object?

If you look at the documentation for the constructor method - it accepts a body parameter and an init options object. The body parameter can be a Blob, so you could;

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);

This would create a Response object that you should be able to pass to your test.

Holsworth answered 18/5, 2017 at 10:9 Comment(5)
Tried the above approach, the issue is still the same. The getTotal function complains about not being able to accept the parameter of type "Response"Eusebioeusebius
@GuruduttShenoy When you use getTotal normally - what is passed to it?Holsworth
Have added a normal call to the getTotal() along with the service call through which it gets the JSON data in the last part of my question posted above. stackoverflow.com/users/297243/thebluefoxEusebioeusebius
. the issue is resolved now. the issue was actually with passing of the parent element 'CompanyResponse' as a part of the JSON file. Returns the expected Response with the standard response interface from FetchApi you mentioned earlier. Thanks a lot for your help :) stackoverflow.com/users/297243/thebluefoxEusebioeusebius
My pleasure @GuruduttShenoy - glad you got it sorted!Holsworth

© 2022 - 2024 — McMap. All rights reserved.