react-hooks-testing-library icon indicating copy to clipboard operation
react-hooks-testing-library copied to clipboard

How to write assertions about an element rendered by a hook?

Open gajus opened this issue 7 years ago • 6 comments

Among other things, my hook is rendering a React element, e.g.

const useFilters = (userConfiguration) => {
  const filtersElement = <div>Hello, World!</div>;

  return {
    filtersElement
  };
};

How do I write assertions about the rendered filtersElement element?, i.e.

// @flow

import React from 'react';
import {
  renderHook
} from 'react-hooks-testing-library';
import useFilters from './useFilters';

it('renders Hello, World!', () => {
  const {result} = renderHook(() => {
    return useFilters();
  });

  // How to get to something equivalent to:
  // expect(result.current.filtersElement.contains(<div>Hello, World!</div>)).toEqual(true);
});

gajus avatar Jun 05 '19 16:06 gajus

Hi @gajus,

There may be a better way, but I'd be tempted to test it like I would any other react component, i.e. using react-testing-library (or enzyme, react-test-render, <insert your favourite react testing library>) to render it. something like:

import React from 'react';
import { renderHook } from 'react-hooks-testing-library';
import { render } from '@testing-library/react';
import 'jest-dom/extend-expect';
import useFilters from './useFilters';

it('renders Hello, World!', () => {
  const { result } = renderHook(() => useFilters());

  const { getByTestId } = render(result.current.filtersElement);

  expect(getByTestId('filter-id')).toHaveTextContent('Hello, World!');
});

Would that work for you?

mpeyper avatar Jun 11 '19 11:06 mpeyper

Closing this now, but happy to reopen for more discussion.

mpeyper avatar Jun 19 '19 13:06 mpeyper

Hi @mpeyper, how might I test a hook that updates an element as a side effect? For example, a counter that might increment the count, but also causes a rendering side effect.

const ProviderWrapper: React.FC = ({ children }) => (
  <CountProvider>{children}</CountProvider>
)

const renderWithProvider = (ui: React.ReactElement, options?: RenderOptions) =>
  render(ui, { wrapper: ProviderWrapper, ...options })

test('renders a count box', () => {
  const { result } = renderHook(() => useCount(), {
    wrapper: ProviderWrapper,
  })

  act(() => {
    result.current.increment()
  })
  
  expect(result.current.count).toBe(1)
  expect(screen.getByRole('alert')).toHaveTextContent(result.current.count)
})

brettinternet avatar Jul 30 '20 06:07 brettinternet

screen is not going to work as we don't render into the DOM when rendering the hook, we use react-test-renderer instead.

I recommend using @testing-library/react and writing a small test component to render if you don't have a component using it already. Don't test the hook, test the component using the hook.

mpeyper avatar Jul 30 '20 08:07 mpeyper

I had to deal with this same situation. The solution was something like this:

const renderToastProviderWithHook = () => {
  const hook: { current: ReturnType<typeof useToastDialog> } = {
    current: {} as ReturnType<typeof useToastDialog>,
  };
  const Component: React.FC = () => {
    hook.current = useToastDialog();
    return null;
  };
  const instance = render(
    <ToastProvider>
      <Component />
    </ToastProvider>
  );
  return {
    ...instance,
    hook,
  };
};

erick-martins avatar Jun 25 '21 19:06 erick-martins

The solution I found was to return the element itself as a provider value, like below:

export const MyElementRendererProvider: React.FC = ({ children }) => {
  // previous code
  const [ element, setElement ] = useState<JSX.Element>(<></>);
  
  useEffect(() => {
    setElement(
      <MyElement foo={foo} bar={bar}>
        {myElementChildren}
      </MyElement>
    )
  }, [ foo, bar, myElementChildren ]);

  return (
    <MyElementRendererContext.Provider value=({ setFoo, setBar, element })>
      {element}
      {children}
    </MyElementRendererContext.Provider>
  );
};

And then render it on the test like below:

it('should render my element component foo info', async () => {
  const { result } = renderHook(() => useMyComponentRenderer(), {
    wrapper: wrapper,
  });

  act(() => {
    result.current.setFoo('foo-content');
  });
  render(result.current.element);

  const element = await screen.findById('my-element-foo');
  expect(element).toBeInTheDocument();
};

arthursoas avatar Feb 23 '22 18:02 arthursoas