玩笑错误:TypeError:stepTwo 不是函数

时间:2021-07-14 16:05:48

标签: reactjs jestjs react-hooks enzyme

我正在尝试测试当用户单击下一个按钮时,我作为 props 传递的函数是否被调用。我已经设置了一个模拟函数,但是当我运行测试时出现以下错误。我看不出哪里出了问题,谢谢。我刚刚包含了组件的主要部分。

控制台错误


      44 |       //    setEmailError(null);
      45 |       // }
    > 46 |       stepTwo(true);
         |       ^
      47 |    };
      48 |
      49 |    const onChange = (e: React.ChangeEvent<HTMLInputElement>): void => {

这是我的测试


test('stepTwo function passed as props is called when all fields have been filled out and the user clicks next', () => {
   const stepTwoMockFunction = jest.fn();
   const stepOneComponent = shallow(<StepOne stepTwo={stepTwoMockFunction} />);
   // React.useState = jest.fn().mockReturnValue([
   //    {
   //       firstNameError: '',
   //       lastNameError: '',
   //       emailError: '',
   //    },
   //    {},
   // ]);
   const nextButton = stepOneComponent.find('[data-test="next-btn"]');
   nextButton.simulate('click', { preventDefault() {} });
   expect(stepTwoMockFunction).toHaveBeenCalledTimes(1);
});

这是我的组件


import React from 'react';

interface Props {
   stepTwo(show: boolean): void;
}

export default function StepOne({ stepTwo }: Props) {
   const [firstName, setFirstName] = React.useState<String>('');
   const [firstNameError, setFirstNameError] = React.useState<String | null>(
      null
   );
   const [lastName, setLastName] = React.useState<string>('');
   const [lastNameError, setLastNameError] = React.useState<string | null>(
      null
   );
   const [email, setEmail] = React.useState<string>('');
   const [emailError, setEmailError] = React.useState<string | null>(null);

   const validateForm = (): void => {
   
      stepTwo(true);
   };




   return (
      <>
         <form>
         
         </form>
         <button onClick={() => validateForm()} data-test='next-btn'></button>{' '}
      </>
   );
}

0 个答案:

没有答案