Can someone assist, please, in following case:
Have a .json response with person's data where, that person can or can not be assigned to some project.
Below is part of response where person is not assigned to project:
"contactPerson": {
"id": "someUUID",
"firstName": "string",
"lastName": "string",
"email": "string",
"title": "string"
},
"project": null
Response where person is assigned to a project:
"contactPerson": {
"id": "someUUID",
"firstName": "string",
"lastName": "string",
"email": "string",
"title": "string"
},
"project": {
"id": "projectUUID",
"name": "This is a project name ",
"fullName": "This is a full project name with over 55 chars",
}
Tried with simple if clause, but without success.
if (typeOf(response.body[i].project.id !== null) {
//assert elements in project array
} else {
//assert is 'null
}
Always got followin error:
Cannot read properties of null (reading 'id')
Does anyone have the idea how to solve it? Assert if there is assigned project or not.
Thank you in advance
In fact, response.body[i].project.id
will be undefined since response.body[i].project
is null
.
It will actually throw an error;
TypeError: Cannot read properties of null (reading 'id')
As mentioned in comments, simply checking response.body[i].project
is enough.
Checking with typeof
on response.body[i].project
will actually return object
.
So either check;
if(response.body[i].project)
This works since null
is falsy
value, and it is equal to doing;
if(response.body[i].project == null)
To actually check if null
;
if(Object.is(response.body[i].project, null))
Or
if(response.body[i].project === null)
const response = {
"contactPerson": {
"id": "someUUID",
"firstName": "string",
"lastName": "string",
"email": "string",
"title": "string"
},
"project": null
};
console.log(response.project); // null
console.log(typeof(response.project)); // object
console.log(response.project == null); // true
console.log(response.project === null); // true
console.log(Object.is(response.project, null)); // true