【问题标题】:useCallback function is not a function while using unit test Jest使用单元测试 Jest 时 useCallback 函数不是函数
【发布时间】:2021-10-12 12:31:26
【问题描述】:

这是我的测试代码 sn-p 但它会引发异常 TypeError: componentInstance.loadLoanApplication is not a function

it('should render the SubmittedLoan', () => {
    const loanData = {
      data: {
        id: 1,
    };

    const div = document.createElement('div');
    const wrapper = mount(
      <AppProviders>
        <MemoryRouter initialEntries={['/review/153']}>
          <SubmittedLoan
            match={{ params: { loanId: 1, step: 1 } }}
            history={{
              location: { state: { from: 'register' } },
              push() {},
            }}
          />
        </MemoryRouter>
      </AppProviders>,
      div,
    );

    const componentInstance = wrapper
      .find(SubmittedLoan)
      .children()
      .first()
      .children()
      .first()
      .instance();
    const loanApplication = {
      id: 1,
      steps_data: [
        { slug: 'step_1', title: 'Step 1' },
        { slug: 'step_2', title: 'Step 2' },
      ],
      status: ApiCaptiq.STATUS_SUBMITTED,
    };

    expect(wrapper.find(SubmittedLoan).length).toBe(1);
    componentInstance.loadLoanApplication(1, 1);
    componentInstance.onLoadLoanApplication(loanData);
    componentInstance.onLoadFail();
    componentInstance.setState({
      formData: [{ item: 'value' }, { item2: 'value2' }],
      activeStep: 1,
      loanApplication,
    });

    componentInstance.handleSnackbarClose(new Event('click'), '');

    componentInstance.setState({ activeStep: 3 });
  });

那么我使用备忘录的组件如下:


export const SubmittedLoan = memo(() => {
  const [loanApplication, setLoanApplication] = useState<LoanApplication | null>(null);
  const [message, setMessage] = useState({
    message: '',
    open: false,
    messageType: '',
  });
  const authContext = useContext(AuthContext);
  const customerContext = useCustomerData();
  const params = useParams();
  const history = useHistory();
  const classes = useStyles();
  const { loanId } = params;

  const onLoadFail = useCallback(() => {
    setMessage({
      message: 'Die verfügbaren Darlehensarten können nicht aufgelistet werden',
      open: true,
      messageType: 'error',
    });
  }, []);

  const onLoadLoanApplication = useCallback(
    (response: AxiosResponse) => {
      setTemplateSettings(response, authContext);
      if (
        response.data.status === ApiCaptiq.STATUS_STARTING ||
        response.data.status === ApiCaptiq.STATUS_IN_PROGRESS ||
        response.data.status === ApiCaptiq.STATUS_PRE_WAITING
      ) {
        history.push(`/view/${loanId}`);
      } else {
        setLoanApplication(response.data);
      }
    },
    [loanId, authContext, history],
  );

  const loadLoanApplication = useCallback(
    async (loan_id: number) => {
      try {
        const response = await request.get(`${ApiCaptiq.LOAN_APPLICATION_URL}${loan_id}/`);
        const { fetchCustomerProfile } = customerContext;
        await fetchCustomerProfile(response.data.customer_profile_id);
        onLoadLoanApplication(response);
      } catch (err) {
        onLoadFail();
      }
    },
    [customerContext, onLoadLoanApplication, onLoadFail],
  );
  ...

这可能是什么原因

【问题讨论】:

    标签: javascript reactjs typescript react-hooks


    【解决方案1】:

    您在组件内部定义的功能不仅仅在组件实例上可用。事实上,没有办法调用它们。您只能通过模拟他们正在执行的 fetch 调用来进行测试。

    如果你真的需要在你的组件中调用函数(你应该尽量避免这些..),你可以使用这个:https://reactjs.org/docs/hooks-reference.html#useimperativehandle

    也许更好的办法是在别处提取此数据加载逻辑并单独测试。

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2019-05-16
      • 2017-07-27
      • 2020-07-31
      • 2018-01-21
      • 1970-01-01
      • 2019-10-01
      • 2018-11-20
      • 2020-02-28
      相关资源
      最近更新 更多