I have an API that returns data in this format -
{
"data": [
{
"id": 121,
"id_type": "some string",
"id_value": "test",
"attribute1": {
"attr_id": 140,
"attribute_client_id": null,
},
"attribute2": {
"attr2_id": 143,
"attribute2_client_id": null,
},
"status": "some string",
"person_name": "James Allen",
"friends": [
{
"friend_id": 1,
"data_id": null,
},
{
"friend_id": 2,
"data_id":null
}
],
"text_description": "Some string",
"text_format": [
"something",
"else"
],
"job_description": "new string",
"is_member": false,
"is_external": false
},
....
]
}
I want to have a function that calculates if of array with is_member
is true.
I can do this in the code itself using the filter
function with something like this - I am using Chakram
library to hit the API end points.
describe('Check if is member is true',()=>{
it('get data',()=>{
let length_of_arr
return response.then((resp)=>{
let length_of_arr = resp.body.data;
length_of_arr.length= Object.keys(length_of_arr).length;
console.log(length_of_arr);
let new_arr = Array.from(length_of_arr);
let r = new_arr.filter(({is_member})=>is_member === true);
console.log(r.length);
expect(r.length).to.be.greater.than(0);
}) ;
});
This works perfectly fine and I am able to get the correct results. However, I need to use this same test for the same API at other places too. So I wanted to have a function which can do it.
In the root directory, I created a file custom_functions.js
, which has code like
module.exports = {
get_member_details(resp,data,attr){
let length_of_arr;
let length_of_arr = resp.body.data;
length_of_arr.length= Object.keys(length_of_arr).length;
console.log(length_of_arr);
let new_arr = Array.from(length_of_arr);
let r = new_arr.filter(({attr})=>attr === true);
console.log(r.length);
}
}
However, this is not correct and it gives error that data
is not defined. How can I achieve this kind of modularisation when using Javascript. I would also welcome if there are suggestions to improve how to approach this problem as well.
As i understand you want to define a function that you can call it in many tests:
//custom_functions.js
function has_member(data){
return data.filter(res => res.is_member).length > 0;
}
module.exports = {
has_member,
}
// in your test you can call this function like this :
const { has_member } require ('./custom_functions');
describe('Check if is member is true',()=>{
it('get data',() => {
return response.then((resp)=>{
const data = resp.body.data;
const has_member = has_member(data);
expect(has_member).to.be.true;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.