How to test conditional rendering component with useQuery result data?

19 views Asked by At

I am testing my React component.
In my component, I use useQuery for category items.
And if there is a data (category array), select element is rendered.

Below is my source.

  const { data: categories, isLoading } = useQuery<ICategoryItem[], boolean>({
    queryKey: ['categoryItem'],
    queryFn: () => getCategoryItem(userId),
    enabled: userId !== '',
  })

return (
{categories && (
            <div>
              <Select
                value={category.label}
                onValueChange={(value) => {
                  const category = categories.filter(
                    (category: ICategoryItem) => {
                      return category._id === value
                    },
                  )[0]
                  setCategory(() => category)
                }}
              >..</div>
}
)

And in my test source, it doesn't find combobox element.
(Error message: TestingLibraryElementError: Unable to find an accessible element with the role "option")

But before using tanstack-query, the test method was success without any problems.

it('test', async () => {
    const user = userEvent.setup()

    const screen = render(<AtvtSection currentDate={new Date()} />)

    await user.click(screen.getByRole('combobox'))
    const comboboxList = screen.getAllByRole('option')
    await user.click(comboboxList[0])

    // ...
  })

So how can I test my component's conditional element with useQuery's result data?
How can I provide caetgories mock data to the component?

I tried below source but that's not working.

function useCustomHook() {
  return useQuery({
    queryKey: ['categoryItem'],
    queryFn: () => {
      return [
        {
          _id: '66001e98d44dc9956110d48a',
          label: '',
          value: 'studying',
          userId: 'public',
        },
        {
          _id: '6602463b6e2d7d198cba1c0f',
          label: '',
          value: 'exercise',
          userId: 'public',
        },
      ]
    },
  })
}

const { result: categories } = renderHook(() => useCustomHook(), {
      wrapper,
    })
    console.log(categories)
    await waitFor(() => categories.current.isSuccess)
    expect(categories.current.data).toBeDefined()
0

There are 0 answers