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!

3
  • 2
    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(); Commented Feb 25, 2021 at 9:29
  • Thank you, this actually solved it! Thought it was some stupid mistake!! Commented Feb 25, 2021 at 9:47
  • Nice! Just posted the answer! Commented Feb 25, 2021 at 9:49

1 Answer 1

7

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

expect(await screen.findByText('select-data')).toBeInTheDocument();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.