我的名为 Alerts 的 ReactJS 组件按日期/名称对 json 数据进行排序,该组件正在工作,但不能在实用程序函数中破坏它的单元测试,这就是问题所在。
Alerts 组件的一部分使用名为 createAlertsWithName 的实用程序函数的一部分。它所做的只是将 2 个数组“合并”为 1 个(因为警报数组不包含名称,而我需要对其进行排序):
export const createAlertsWithName = (alerts,applicants) =>{
return alerts.map(a =>({
...a,
name:(a.applicants
.map(id =>getApplicantByid(id,applicants))
.find(applicant => applicant.isPrimaryApplicant) ||{lastName:''}).lastName
}))
}
当我运行“npm test”时,我收到以下错误消息:
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)
这看起来很奇怪,因为我在没有像这样的 find 语句的情况下检查了“name”属性:
name:(a.applicants
.map(id =>getApplicantByid(id,applicants))
输出将是:
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"
据我所知,它不会返回未定义的“名称”。那么为什么我会收到“无法读取未定义的属性‘isPrimaryApplicant’”错误?
最佳答案
peopleMock.alerts[X].applicants
中的 ids(?) 与 peopleMock.applicants[X].id
中的任何 id 都不匹配。这会导致 getApplicantByid
返回 undefined
,从而导致 applicant.isPrimaryApplicant
为 undefined
。如果将 peopleMock.alerts[X].applicants
中的 id 更新为 peopleMock.applicants[X].id
中的 id,则测试将运行。我不确定输出是否是您所期望的。您可能需要更新createAlertsWithName
函数以合理的方式处理undefined
。
也许是这样的:
.find(applicant => applicant && applicant.isPrimaryApplicant) ||
{
lastName: ""
}
关于javascript - 为什么 Jest 单元测试被破坏了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54385054/