VBAHole
VBAHole

Reputation: 1518

React test function passed to child component

I have a simple react app with a Parent component that has a function to make an xhr call. This function gets passed down to a child component whose job is to collect some info from the user and then on a submit button call the prop handler. That then calls the function in the parent. All well and good and working for me.

I have tested the child to make sure the button click causes the handler to be fired. Works well.

Now I want to test the actual handler code in the Parent. How can I do that? I don't have an event in the Parent that I can fire, that happens in the child.

I'm not doing a great job of explaining, I realize that. I am using @testing-library/react and jest.

I'm really just trying to test js code that happens to be inside of this component. One suggestion I saw was to extract this function out of the component, export it, and test it that way. But this code modifies the parent component state so I don't see how I can abstract that out.

What code I do have is meager, apologies:

  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

      });
    });

This is some pseudo parent component code:

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;

Upvotes: 7

Views: 1897

Answers (1)

zapala.grzegorz
zapala.grzegorz

Reputation: 103

I've been working on something similiar.

With react-testing-library it was possible this way.

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

Upvotes: 1

Related Questions