How to write a test for nested JSON response from enterprise application - arrays

I'm trying to use Postman as a test tool to validate that our customers all have a mailing address in our master system. I'm having trouble drilling down into the JSON due to its structure. Each response is an array structure with a single "node" that has no "head attribute" to address.
Example JSON:
[
{
"ID": "cmd_org_628733899",
"organization": {
"name": "FULL POTENTIAL",
"accountStatusCode": "1",
"accountStatusDescription": "OPEN"
},
"location": [
{
"locality": "LITTLE ROCK",
"locationType": "MAILING"
},
{
"locality": "BIG ROCK",
"locationType": "LOCATION"
}
]
}
]
Test code as it exists:
pm.test("Check for a Mailing Address", function () {
// Parse response body
var jsonData = pm.response.json();
// Find the array index for the MAILING Address
var mailingLocationIndex = jsonData.location.map(
function(filter) {
return location.locationType;
}
).indexOf('MAILING');
// Get the mailing location object by using the index calculated above
var mailingLocation = jsonData.location[mailingFilterIndex];
// Check that the mailing location exists
pm.expect(mailingLocation).to.exist;
});
Error message: TypeError: Cannot read property 'map' of undefined
I understand that I have to iterate to node(0) in the outer array and then drill into the nested location array to find an entry with a locationType = Mailing.
I can't get past the outer array. I'm new to JavaScript and JSON parsing - I am a COBOL programmer.

Knowing nothing else, I would say you mean this
pm.test("Check for a Mailing Address", function () {
var mailingLocations = pm.response.json().location.filter(function (item) {
return item.locationType === 'MAILING';
});
pm.expect(mailingLocations).to.have.lengthOf(1);
});
You want to filter out all the locations that have a MAILING type and there should be exactly one, or at least one, depending.
Whether pm.response.json() actually returns the object you show in your question is impossible to say from where I'm standing.
In modern JS, the above is shorter:
pm.test("Check for a Mailing Address", function () {
var mailingLocations = pm.response.json().location.filter(item => item.locationType === 'MAILING');
pm.expect(mailingLocations).to.have.lengthOf(1);
});

Related

Javascript looping through an object

I have an object which is given back through my REST API and I need to iterate through it for synchronizing a DB. So the object contains another object called tables. The tables object has different arrays with table names and their key value pairs.
I could not loop through the tables object about two days whatever I did and it is really annoying getting null or undefined values back.
For example I tried iterating through the table array with the JavaScript function object.forEach((article)=>console.log(article.id,article.name));
const obj = response.content.tables.article;
function findArticles(obj) {
obj.forEach((article)=>console.log(article.id,article.name));
}
I can't get any value back. When I try to console.log(response.content); it shows me everything. As soon as I try to output response.content.tables it says undefined.
This is the structure of the object response.content:
{
"status": "1",
"message": "sync out request successfull",
"tables": {
"article": [
{
"id": 1,
"name": "baseball"
},
{
"id": 2,
"name": "truck"
},
],
"food": [],
"animals: []
}
}
Try converting the response to an object using JSON.parse(xyz) before attempting to get the properties.
var xyz = '{ "status": "1", "message": "sync out request successfull", "tables": { "article": [{"id": 1,"name": "baseball"},{"id": 2,"name": "truck"}],"food": [],"animals": []}}'
var obj = JSON.parse(xyz);
$(obj.tables).each(function (ix, el) {
console.log(el)
});
I solved it like this:
var obj = response.content;
var JSON = JSON.parse(obj);
var articleTable = JSON.tables.article;
articleTable.forEach((article)=>console.log(article.id,article.name));
After I parsed the response.content object to JSON it was available to access the nested objects as 'tables' and 'article'. After passing the article object with the articleTable variable to the forEach it has been possible to access each elements. Now I get results.
I really appreciate your help
T3.0 it wasn't able to solve the problem without you.

AngularJS - Calling values in response with Spring GET

New here so my description might be bad but I'm trying to access the values on the second level of my JSON but I can't seem to get it. It only brings the values of the top level.
My JSON body looks like the following:
{
"services": [
{
"nameLevel1": "Example1",
"secondServices": [
{
"id": 1,
"namelevel2": "Example2",
}
]
}
]
}
And when I call it, I only can get the nameLevel1 and that is it. My GET method is this:
$scope.retrieveServices = function (id) {
SpringDataRestService.get(
{
"collection": "user",
"resource": id
},
function (response) { // Success Function
$scope.userServices = response.services;
$scope.recievedValues = true;
}
);
};
Now I originally thought all I would have to do is:
$scope.userServices = response.services.secondServices;
But I'm getting an undefined issue. So my query is how do I access all of them? My JSON body when doing a log output does show everything, but for some reason I can't seem to get it to show everything in my table. Only the nameLevel1 values.
Any help would be appreciate, and I hope my description is okay. Edits would be get as well since not too sure if I have labelled this correctly. Thank you!

equalTo returning null from Firebase?

In my React Native App, I currently am trying to pull all items that have the selected property set to "true" from the database. However, when I log the results of this query, they are all being returned as null (even though expected response should be returning two objects). My relevant code as well as Firebase structure are included below, please let me know if you spot anything.
const rootRef = new Firebase(`${ config.FIREBASE_ROOT }`)
var queryRef = rootRef.orderByChild("items/selected");
var solution = queryRef.equalTo("true").once('value', function(snap) {
console.log(snap.val())
});
Firebase JSON:
"items":
[
{
"title":"ball",
"selected": "false"
},
{
"title":"dog",
"selected": "true"
},
{
"title":"phone",
"selected": "false"
},
{
"title":"cup",
"selected": "true"
}
],
When you run an Firebase query on a location, it takes each child node under that location and then evaluates the condition you specify. If you take each child under items, you'll see there is no path items/selected under there.
You query is instead:
var itemsRef = rootRef.child("items");
var queryRef = itemsRef.orderByChild("selected");
You should use
where("selected" = true)
instead of equalTo()

I try to implement a connection using relay and all the node's IDs are the same

I write a really simple schema using graphql, but some how all the IDs in the edges are the same.
{
"data": {
"imageList": {
"id": "SW1hZ2VMaXN0Og==",
"images": {
"edges": [
{
"node": {
"id": "SW1hZ2U6",
"url": "1.jpg"
}
},
{
"node": {
"id": "SW1hZ2U6",
"url": "2.jpg"
}
},
{
"node": {
"id": "SW1hZ2U6",
"url": "3.jpg"
}
}
]
}
}
}
}
I posted the specific detail on github here's the link.
So, globalIdField expects your object to have a field named 'id'. It then takes the string you pass to globalIdField and adds a ':' and your object's id to create its globally unique id.
If you object doesn't have a field called exactly 'id', then it wont append it, and all your globalIdField will just be the string you pass in and ':'. So they wont be unique, they will all be the same.
There is a second parameter you can pass to globalIdField which is a function that gets your object and returns an id for globalIdField to use. So lets say your object's id field is actually called '_id' (thanks Mongo!). You would call globalIdField like so:
id: globalIdField('Image', image => image._id)
There you go. Unique IDs for Relay to enjoy.
Here is the link to the relevant source-code in graphql-relay-js: https://github.com/graphql/graphql-relay-js/blob/master/src/node/node.js#L110
paste the following code in browser console
atob('SW1hZ2U6')
you will find that the value of id is "Image:".
it means all id property of records fetched by (new MyImages()).getAll()
is null.
return union ids or I suggest you define images as GraphQLList
var ImageListType = new GraphQL.GraphQLObjectType({
name: 'ImageList',
description: 'A list of images',
fields: () => ({
id: Relay.globalIdField('ImageList'),
images: {
type: new GraphQLList(ImageType),
description: 'A collection of images',
args: Relay.connectionArgs,
resolve: (_, args) => Relay.connectionFromPromisedArray(
(new MyImages()).getAll(),
args
),
},
}),
interfaces: [nodeDefinition.nodeInterface],
});

Trouble with updating object properties in AngularJs

I am building my first app in AngularJs.
Here is the plunkr with what I've done so far. The user should be able to add new websites and group them in groups. Groups are also made by the user. Any time the new group is created it is available for new websites. What app should also do is to update group objects with newly assigned websites... and this is where I fail.
Here is how json should look like:
{
"sites": [
{
"url": "http://sfdg",
"id": 0,
"groups": [
{
"name": "adsf",
"id": 0
}
]
}
],
"groups": [
{
"name": "adsf",
"id": 0,
"sites": [//sites assigned
]
}
]
}
In the plunkr code I used push but that just adds new group...
Could you please direct me to the right way of achieving this.
Thanks!
To prevent circular references (a website object refers to a group object that refers to the website object, etc...), I would store id's to the relevant objects instead.
First, when creating a new group, add an empty sites array to it:
function createGroup(newGroup) {
newGroup.sites = []; // <-- add empty array of sites
$scope.groups.push(newGroup);
newGroup.id = groupIdSeq;
groupMap[newGroup.id] = newGroup;
groupIdSeq++;
return newGroup;
}
Then, when you create a new site, update each group to which the site is added:
function createSite(newSite, groups) {
$scope.sites.push(newSite);
newSite.id = siteIdSeq;
sitesMap[newSite.id] = newSite;
// instead of storing the groups array, only store their id:
newSite.groups = groups.map(function(group) { return group.id });
// and add this new sites id to the groups' sites array.
groups.forEach(function(group) {
group.sites.push(newSite.id);
});
siteIdSeq++;
return newSite;
}
(updated plunker here)

Resources