[英]How can I mock this function in jest react test?
In my jest snapshottest I have: 在我开玩笑的快照测试中,我有:
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',
}];
In the actual component AlertsContainer I have a function: 在实际的组件AlertsContainer中,我具有一个功能:
getApplicantByid = id => _.find(this.props.getApplicants, { id });
When I run the test I get: 当我运行测试时,我得到:
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 |
How can I mock this this.getApplicantByid(id) call? 我如何模拟this.getApplicantByid(id)调用?
As far as I know you can not mock component instance methods. 据我所知,您不能模拟组件实例方法。 One thing you could do however is spy on lodash find before your test 但是,您可以做的一件事是在测试前对lodash进行监视
import _ from 'lodash'
In your describe block it would look something like 在您的描述块中,它看起来像
let mock
beforeEach(() => {
mock = jest.spyOn(_, 'find').mockReturnValue(applicantsMock[0]);
});
Additionally you could test if it retrieves the applicants correctly like so 此外,您可以像这样测试它是否正确检索了申请人
it('it retrieves the applicant', () => {
const component = withTheme(
<AlertsContainer alerts={alertsMock} getApplicants={applicantsMock} />
);
const wrapper = shallow(component).dive();
expect(mock).toHaveBeenCalledWith(applicantsMock[0].id)
})
Hope this helped! 希望这对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.