React 测试函数传递给子组件

VBA*_*ole 6 reactjs

我有一个简单的 React 应用程序,其父组件具有进行 xhr 调用的功能。该函数被传递给一个子组件,该子组件的工作是从用户收集一些信息,然后在提交按钮上调用 prop 处理程序。然后调用父级中的函数。一切都很好,为我工作。

我已经测试了孩子,以确保单击按钮会导致处理程序被触发。效果很好。

现在我想测试父级中的实际处理程序代码。我怎样才能做到这一点?我在父级中没有可以触发的事件,而这发生在子级中。

  • 父级(submitHandler 函数和另一个处理单击事件的函数[这是我要测试的])将submitHandler 传递给子级
  • 子级(其单击事件触发父级中的submitHandler 的按钮)

我意识到我没有很好地解释这一点。我正在使用 @testing-library/react 和玩笑。

我真的只是想测试恰好位于该组件内部的js代码。我看到的一个建议是从组件中提取这个函数,将其导出,然后以这种方式进行测试。但是这段代码修改了父组件状态,所以我不知道如何将其抽象出来。

我所拥有的代码很少,抱歉:

  describe('Testing Parent Component', () => {
      const setup = () => {
        render(<Parent />);
      };
    
      test('child click event fires', async () => {
        // here I want to mock the child firing the Parent's handler function

      });
    });
Run Code Online (Sandbox Code Playgroud)

这是一些伪父组件代码:

import React, { useEffect } from 'react';
import Child from './child';

const Parent = () => {
  const [queueStatus, setQueueStatus] = React.useState([]);
  const [data, setData] = React.useState(true);

  useEffect(() => {
    fetchStatus();
  }, []);

  const fetchStatus = async () => {
    setIsFetching(true);
    // get some data
    setIsFetching(false);
    setData(fetchedData);
  };

  // I want to test this 
  const submitHandler = async (childprop1) => {
    // do something else but then refresh
    fetchStatus();
  };

  return (
      <Child submitHandler={submitHandler} />
  );
};

export default Parent;
Run Code Online (Sandbox Code Playgroud)

zap*_*orz 1

我一直在做类似的事情。

使用react-testing-library,这种方式是可能的。

it("sets up active directory", async () => {
         const user = userEvent.setup();

         renderWithProviders(<DirectoriesList />);
         const button = await screen.findByRole("button", { name: /dir1/i });

         const subItem = screen.queryByText(/dir2/i);
         expect(subItem).not.toBeVisible();

         
         
         /* it clicks subcomponent, which changes parent state */
       
         await user.click(button);
       
         const subItemShowed = screen.getByText(/dir2/i);
         expect(subItemShowed).toBeVisible();
  });
Run Code Online (Sandbox Code Playgroud)