繁体   English   中英

如何在玩笑反应测试中模拟此功能?

[英]How can I mock this function in jest react test?

在我开玩笑的快照测试中,我有:

it('should render Alerts', () => {
const component = withTheme(
<AlertsContainer alerts={alertsMock} getApplicants={applicantsMock} />
);
const wrapper = shallow(component).dive();
expect(wrapper).toMatchSnapshot();
});

const applicantsMock = [
{
   firstName: 'John',
   lastName: 'Sharma',
   idScheme: 'CustomerInternalId',
   isPrimaryApplicant: true,
   applicantSerialNumber: 1,
   id: '000000797',
}]

const alertsMock = [
{
   taskType: 'Pending',
   taskName: 'Task1',
   subject: 'Review',
   submissionId: 'SUB200620150000875',
   createdBy: 'testuser',
   createdDateTime: '2018-06-14T00:00:00.000Z',
   assignedDateTime: '2018-06-15T00:00:00.000Z',
   dueDateTime: '2018-06-21T00:00:00.000Z',
   applicants: ['16671520038', '16671520039'],
   id: '05025fea-ec37-4767-a868-a646597365d0',
}];

在实际的组件AlertsContainer中,我具有一个功能:

getApplicantByid = id => _.find(this.props.getApplicants, { id });

当我运行测试时,我得到:

TypeError: Cannot read property 'isPrimaryApplicant' of undefined

      121 |         name: a.applicants
      122 |           .map(id => this.getApplicantByid(id))
    > 123 |           .find(applicant => applicant.isPrimaryApplicant).lastName,
          |                                     ^
      124 |       }));
      125 |   };
      126 |

我如何模拟this.getApplicantByid(id)调用?

据我所知,您不能模拟组件实例方法。 但是,您可以做的一件事是在测试前对lodash进行监视

import _ from 'lodash'

在您的描述块中,它看起来像

let mock

beforeEach(() => {
  mock = jest.spyOn(_, 'find').mockReturnValue(applicantsMock[0]);
});

此外,您可以像这样测试它是否正确检索了申请人

it('it retrieves the applicant', () => {
  const component = withTheme(
    <AlertsContainer alerts={alertsMock} getApplicants={applicantsMock} />
  );
  const wrapper = shallow(component).dive();

  expect(mock).toHaveBeenCalledWith(applicantsMock[0].id)
})

希望这对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM