Reputation: 22580
My reactjs component called Alerts sorts json-data by date/name, the component is working but not the unit test it breaks in a utilityfunction, this is the issue.
Part of the Alertscomponent uses a part of a utility function called createAlertsWithName. All it does is 'merging' 2 arrays into 1(because the alerts array does not contain a name and I need this to sort) :
export const createAlertsWithName = (alerts,applicants) =>{
return alerts.map(a =>({
...a,
name:(a.applicants
.map(id =>getApplicantByid(id,applicants))
.find(applicant => applicant.isPrimaryApplicant) ||{lastName:''}).lastName
}))
}
When I run 'npm test' I get the following error message:
Alerts › should render sorted data
TypeError: Cannot read property 'isPrimaryApplicant' of undefined
6 | name:(a.applicants
7 | .map(id =>getApplicantByid(id,applicants))
> 8 | .find(applicant => applicant.isPrimaryApplicant) ||{lastName:''}).lastName
| ^
9 | }))
10 | }
11 |
at isPrimaryApplicant (src/utility.js:8:38)
at Array.find (<anonymous>)
at find (src/utility.js:8:10)
at Array.map (<anonymous>)
at map (src/utility.js:4:19)
at createAlertsWithName (src/utility.js:17:12)
at Alerts.render (src/Alerts.js:12:11)
This seems strange because I checked the 'name' property without the find-statement like this:
name:(a.applicants
.map(id =>getApplicantByid(id,applicants))
The output would be:
applicants: (2) ["000001262", "000001263"]
assignedDateTime: "2018-10-25T09:25:00Z"
createdDateTime: "2019-10-24T09:25:00Z"
dueDateTime: "2019-10-25T09:25:00Z"
id: "19d0da63-dfd0-4c00-a13a-cc822fc81297"
name: (2) [{…}, {…}]
subject: "What a nice day"
submissionId: "SUB200620150004197"
__proto__: Object
1:
applicants: ["000001201"]
assignedDateTime: "2018-10-25T09:25:00Z"
createdDateTime: "2018-10-24T09:25:00Z"
dueDateTime: "2018-10-25T09:25:00Z"
id: "19d0da63-dfd0-4c00-a13a-cc822fc81201"
name: [{…}]
subject: "Hello"
submissionId: "SUB200620150004201"
And it does not return an undefined 'name' as far as I can see. So why do I get the 'Cannot read property 'isPrimaryApplicant' of undefined' error ?
Upvotes: 0
Views: 136
Reputation: 843
The ids(?) in peopleMock.alerts[X].applicants
don't match any of the ids in peopleMock.applicants[X].id
. This causes getApplicantByid
to return undefined
causing applicant.isPrimaryApplicant
to be undefined
. If you update the ids in peopleMock.alerts[X].applicants
to the ids in peopleMock.applicants[X].id
, the test runs. I'm not sure if the output is what you expect though. You'll probably want to update the createAlertsWithName
function to handle the undefined
in a reasonable way.
Maybe something like:
.find(applicant => applicant && applicant.isPrimaryApplicant) ||
{
lastName: ""
}
Upvotes: 1