为什么笑话单元测试坏了?

时间:2019-01-27 04:20:02

标签: javascript reactjs unit-testing jestjs enzyme

我的称为Alerts的reactjs组件按日期/名称对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'属性,但没有这样的查找语句:

 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'错误”?

1 个答案:

答案 0 :(得分:1)

peopleMock.alerts[X].applicants中的id(?)与peopleMock.applicants[X].id中的任何id不匹配。这导致getApplicantByid返回undefined,导致applicant.isPrimaryApplicantundefined。如果将peopleMock.alerts[X].applicants中的ID更新为peopleMock.applicants[X].id中的ID,则测试将运行。我不确定输出是否是您期望的。您可能需要更新createAlertsWithName函数以合理的方式处理undefined

也许像这样:

.find(applicant => applicant && applicant.isPrimaryApplicant) || 
  {
    lastName: ""
  }