[英]Why is jest unit test broken?
我的reactjs組件Alerts按日期/名稱對json數據進行排序,該組件正在運行,但未在實用程序功能中中斷的單元測試,這就是問題所在。
Alerts組件的一部分使用稱為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)
這似乎很奇怪,因為我檢查了'name'屬性而沒有這樣的find語句:
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
的id(?)與peopleMock.applicants[X].id
中的任何id不匹配。 這將導致getApplicantByid
返回undefined
導致applicant.isPrimaryApplicant
是undefined
。 如果將peopleMock.alerts[X].applicants
中的ID更新為peopleMock.applicants[X].id
的ID, peopleMock.applicants[X].id
運行測試。 我不確定輸出是否是您期望的。 您可能需要更新createAlertsWithName
函數,以合理的方式處理undefined
的內容。
也許像這樣:
.find(applicant => applicant && applicant.isPrimaryApplicant) ||
{
lastName: ""
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.