React Testing Library, Portals, MUI Autocomplete

Julius Koronci
1 min readJun 26, 2020

--

Anyone wanting to test portals with react testing library runs into problems eventually. There are a few ways to test portals but sometimes with external libraries like Mui Autocomplete we have to compromise.

Ideally we can provide the portal root and pass this as wrapper to render, if this doesn't work we can try mocking ReactDom.createPortal and if this doesn't work, here is how I did it within my project. (Not saying its the best solution but it certainly works :))

test('Form with Autocomplete using Portal', async () => {
let rendered: ReturnType<typeof render>;

await act(() => {
rendered = render(<Form />, { wrapper: Wrapper, container: document.body });
});

const { findByPlaceholderText, getByText } = rendered;

const autocomplete = await findByPlaceholderText('Select Option');
fireEvent.mouseDown(autocomplete); const { getByText: getByBodyText } = within(document.body); const option = getByBodyText('BuBuBu'); expect(option).toBeInTheDocument(); fireEvent.click(option as HTMLElement);

expect(autocomplete).toHaveProperty('value', 'BuBuBu');
});

Whats important here, we say the container is document body (although not recommended it works).

We do our testing logic as usual but we use within(document.body) to find elements.

Hope this saves someone a lot of googling, enjoy :)

--

--