Postman - how to check if one of three fields it not null - postman

I am getting an API response which provides a variety of fields. Among them, there are three fields, where 2 of the 3 fields will be null and one will not be null.
How do I check, among the three fields, one is not null?

At least one not null
You can use the Object.values() and some() if you want at least one to be not null.
pm.test("One not null", () => {
const parsedResponseBody = pm.response.json();
pm.expect(Object.values(parsedResponseBody).some(v => v !== null)).to.be.true;
})
Test will success for a response body like this:
{
"prop1": null,
"prop2": null,
"prop3": "notNull"
}
and for a response body like this:
{
"prop1": null,
"prop2": "notNull",
"prop3": "notNull"
}
Exactly one not null
If you don't know what the other values will be
For exactly one you can just count the occurrences of a specific value (null in this case) using reduce().
This is most-likely what you want and it's very simple to customize e.g. if you suddenly want exactly 2, 3, 4, etc. values to be non-null.
pm.test("Expected count not null", () => {
const parsedResponseBody = pm.response.json();
const expectedCount = 1;
pm.expect(
Object.values(parsedResponseBody)
.reduce((total, value) => value !== null ? total + 1: total, 0)
).to.equal(expectedCount);
})
Test will success for a response body like this:
{
"prop1": null,
"prop2": null,
"prop3": "notNull"
}
but fail for a response body like this
and for a response body like this:
{
"prop1": null,
"prop2": "notNull",
"prop3": "notNull"
}
If you know what the other property values will be
If you know which values the other properties will have you can also use the following approach using all.members()
pm.test("Expected count not null", () => {
const parsedResponseBody = pm.response.json();
pm.expect(Object.values(parsedResponseBody)).to.have.all.members([null, null, "notNull"])
})

Related

Postman = To assert that the array in the response body contains a string value in all its elements

I'm new to Postman. My Postman is failing to match test criteria. Could anyone please help! It is returning true even if there is no match
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData.attributes, (item) => {
pm.expect(item.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})
{
"id": "423317",
"type": "space",
"attributes": {
"name": "RM_05_030",
"space_ref_id": "RM_05_030",
"building_ref_id": "80_Fen",
"floor_ref_id": "5"
}
}
I assume that the code above is incomplete and that the response is actually and array of objects and that jsonData contains the parsed response body as a JavaScript array of objects.
The _.each() function takes an array as its first parameter, so you should not pass jsonData.attributes. This is the reason that your test passed; jsonData.attributes isn't an array, your callback will never get executed and no failing assertions means a succeeding test.
You can iterate over jsonData and assert that every item has a nested attribute item.attributes.building_ref_id containing your string:
jsonData = pm.response.json()
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData, (item) => {
pm.expect(item.attributes.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})

adding record from one List to another List

In List One, I am getting some items. Each time those items are changing. Sometimes, I can get more than one record in the List.
In a second List, I would like to store all the data of List One. So, I can then display all the items of List Two.
To make it more clear.
List One = "/temp/file1.jpeg"
List Two = "/temp/file1.jpeg"
List One = "/temp/file2.jpeg"
List Two = "/temp/file1.jpeg,/temp/file2.jpeg"
I have tried this
void _openDocumentFileExplorer({fileType: FileType.custom}) async {
setState(() => _loadingPath = true);
try{
_paths = (await FilePicker.platform.pickFiles(
type: fileType,
allowMultiple: true,//_multiPick,
allowedExtensions: ['pdf']))?.files;
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
} catch (ex) {
print('$ex');
}
if (!mounted) return;
setState(() {
_loadingPath = false;
_fileName = _paths != null ?
_paths!.map((e) => e.name).toString() : '...';
});
}
ListView.separated(
itemCount:
_paths != null && _paths!.isNotEmpty
? _paths!.length
: 1,
itemBuilder:
(BuildContext context, int index) {
final bool isMultiPath =
_paths != null && _paths!.isNotEmpty;
final String name = _paths!
.map((e) => e.name)
.toList()[index];
//filesGB store the full path + the file name
final filesGB = _paths!
.map((e) => e.path)
.toList()[index]
.toString();
print (filesGB);
_paths?.addAll(allFiles!.map((e) ));
allFiles.addAll(filesGB.toList());
allFiles.addAll(filesGB);
// allFilesV2.addAll(filesGB);
but it does not work. I am getting this error message.
"The argument type 'String' can't be assigned to the parameter type 'Iterable'"
Please, do you have any suggestion?
I think you can use SPREAD OPERATOR (...) using a triple dot for merging one array into another.
For example:
List list1= ["/temp/file1.jpeg"];
List list2 = [];
after some time
list1 = ["/temp/file2.jpeg"];
so whenever your list one change do
list2 = [...list2,...list1];
print(list2);
output: ["/temp/file1.jpeg","/temp/file2.jpeg"]
I think it would help.

get response from expo sqlite query

According to Expo documentation with SQLite I would make a query like so:
tx.executeSql(sqlStatement, arguments, success, error)
I execute it like this:
db.transaction(tx => {
tx.executeSql('SELECT * FROM dr_report_properties WHERE orderId = (?)', [this.state.orderId]);
},
error => {
alert(error);
},
(tx, results) => {
console.log(results);
}
);
My question is how do I get the response? The above returns as undefined.
I then try (not expecting it to work but just for kicks)
console.log(tx);
This does give a console.log
(tx, results) => {
console.log('I got data');
}
)
According to the documentation:
ResultSet objects are returned through second parameter of the success callback for the tx.executeSql() method on a Transaction (see above). They have the following form:
{
insertId,
rowsAffected,
rows: {
length,
item(),
_array,
},
}
I would expect result would be this object. Any ideas at what I'm doing wrong?
The problem with the above was that I placed the call AFTER the execution it's actually in the same method as that.
The result should have gone in the callback like so:
db.transaction(
tx => {
tx.executeSql('select * from my_table', [], (trans, result) => {
console.log(trans, result)
});
}
);
Thanks to #charliecruzan from expo team!

Refetch queries with any combination of parameters

I have faced with a problem when refetching queries after mutation. If query has no parameters thats ok, but if query has several parameters, and different pages uses different of them. For example, GET_ITEMS query accepts parameters: userId, companyId, categoryId. How can I say to Apollo to refetch all this queries with any combination of parameters?
It seem there is no way I can make it now with Apollo Client. So I had to save the parameters of all GET_ITEMS calls from all pages, and then transfer the saved parameters to the refetchQueries mutation method. The code turned out like this:
ItemsContext.js
const ItemsContext = React.createContext({
cachedQueryVars: [],
});
ItemsList.js
...
render() {
...
return <ItemsContext.Consumer>{({cachedQueryVars}) => {
cachedQueryVars.push(variables);
return <Query query={GET_ITEMS} variables={variables} >
...
ItemEdit.js
...
render() {
...
return <ItemsContext.Consumer>{({cachedQueryVars}) =>
<Mutation mutation={UPDATE_ITEM_MUTATION}
refetchQueries={({data}) => this.handleRefetchQueries(data.updateItem, cachedQueryVars)}
...
}
handleRefetchQueries(newItem, cachedItemsQueryVars) {
let result = [];
let filtered = null;
if(this.state.oldCategoryId != newItem.category.id) {
filtered = cachedItemsQueryVars.filter(v => v.categoryId == this.state.oldCategoryId);
result = this.concatItemQueryVars(result, filtered);
filtered = cachedItemsQueryVars.filter(v => v.categoryId == newItem.category.id);
result = this.concatItemQueryVars(result, filtered);
}
if(this.state.oldCompanyId != newItem.company.id) {
filtered = cachedItemsQueryVars.filter(v => v.companyId == this.state.oldCompanyId);
result = this.concatItemQueryVars(result, filtered);
filtered = cachedItemsQueryVars.filter(v => v.companyId == newItem.company.id);
result = this.concatItemQueryVars(result, filtered);
}
...
return result;
}
concatItemQueryVars(result, filtered) {
return result.concat(filtered.map(v => ({
query: GET_ITEMS,
variables: v
})));
}

Postman API testing: Unable to assert a value is true

I am testing an API with a GET request that returns the following data:
{
"Verified": true,
"VerifiedDate": 2018-10-08
}
I am trying to test that the first field comes back true, and the second field has a value. I have the following code:
pm.test("Verified should be true", function () {
var Status = pm.response.json();
pm.expect(Status.Verified).to.be.true;
});
pm.test("Returns a verified date", function () {
var Status = pm.response.json();
pm.expect(Status.VerifiedDate).to.not.eql(null);
});
The assert on true is failing for the following reason:
Verified should be true | AssertionError: expected undefined to be true
Why is the first test failing?
I am running the same test on a post command without any issues.
Any ideas?
thanks
Root cause:
Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.
Solution:
Use exactly value of an item in the list with if else command to compare.
var arr = pm.response.json();
console.log(arr.length)
for (var i = 0; i < arr.length; i++)
{
if(arr[i].Verified === true){
pm.test("Verified should be true", function () {
pm.expect(arr[i].Verified).to.be.true;
});
}
if(arr[i].Verified === false){
pm.test("Verified should be false", function () {
pm.expect(arr[i].Verified).to.be.false;
});
}
}
Hope it help you.
You could also just do this:
pm.test('Check the response body properties', () => {
_.each(pm.response.json(), (item) => {
pm.expect(item.Verified).to.be.true
pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
})
})
The check will do a few things for you, it will iterate over the whole array and check that the Verified property is true and also check that the VerifiedDate is a string and matches the YYYY-MM-DD format, like in the example given in your question.