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

时间:2019-01-25 09:09:56

标签: javascript reactjs unit-testing jestjs

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

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)调用?

1 个答案:

答案 0 :(得分:-1)

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

import _ from 'lodash'

在您的describe块中,它看起来像

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)
})

希望这对您有帮助!