How to test components using react-query with msw and react-testing-library?
Asked Answered
S

1

5

I have a page with a dropdown component being loaded into it. This component calls a customhook that uses react query to get data to show in the dropdown. On initial load this component is in a loading state and renders a loading icon. When react-query finishes the call successfully the component renders the list of data into the dropdown.

const SelectItem = ({ handleSelectChange, selectedItem }) => {
  
  const { data, status } = useGetData(url, 'myQueryKey');

  if (status === 'loading') {
    return <RenderSkeleton />;
  }

  if (status === 'error') {
    return 'An Error has occured';
  }

  return (
    <>
      <Autocomplete
        options={data}
        getOptionLabel={(option) => `${option.name}`}
        value={selectedItem}
        onChange={(event, newValue) => {
          handleSelectChange(newValue);
        }}
        data-testid="select-data"
        renderInput={(params) => <TextField {...params}" />}
      />
    </>
  );
};

How do I test this correctly? my test only renders the Skeleton component even after implementing msw to mock the response data. So I assume it basically only awaits the "isLoading" state.

it('should load A Selectbox data', async () => {
  render(
    <QueryClientProvider client={queryClient}>
      <SelectItem />
    </QueryClientProvider>
  );
  expect(await screen.getByTestId('select-data')).toBeInTheDocument()
});

Please note I also implemented msw mock server and handlers to mock the data it should return. BTW Before using react query It worked like a charm, so I guess I am overseeing something.

Thank you!

Sites answered 25/2, 2021 at 9:23 Comment(3)
Your mocked data is returning a promise with some timeout? Did you try using findByText (will wait for the DOM element) from react-testing-library like; expect(await screen.findByText('select-data')).toBeInTheDocument();Preceptor
Thank you, this actually solved it! Thought it was some stupid mistake!!Sites
Nice! Just posted the answer!Preceptor
P
7

Try using findByText (will wait for the DOM element, returning a Promise)

expect(await screen.findByText('select-data')).toBeInTheDocument();
Preceptor answered 25/2, 2021 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.