为什么 Jest 单元测试失败了?
2019-01-27
131
我的 reactjs 组件 Alerts 按日期/名称对 json 数据进行排序,该组件可以正常工作,但单元测试无法正常工作,它在实用程序函数中中断了该测试,这就是问题所在。
Alertscomponent 的一部分使用了实用程序函数 createAlertsWithName 的一部分。它所做的就是将 2 个数组“合并”为 1 个(因为 alerts 数组不包含名称,而我需要它进行排序):
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"
据我所知,它不会返回未定义的“name”。那么为什么我会收到“无法读取未定义的属性‘isPrimaryApplicant’”错误?
1个回答
peopleMock.alerts[X].applicants
中的 id(?) 与
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: ""
}
Karl Galvez
2019-01-27