React Testing Examples

react-testing-library
GitHubAbout
All examples

The component is styled using styled-components themes. This means the component requires ThemeProvider context.

We're not testing style output here. The purpose of this test is merely to illustrate how to use ThemeProvider in tests.

test.js
// Hoist helper functions (but not vars) to reuse between test cases
const renderComponent = ({ theme, name }) =>
render(
<ThemeProvider theme={theme}>
<HelloMessageStyled name={name} />
</ThemeProvider>
);
it('renders greeting', async () => {
// Render new instance in every test to prevent leaking state
const { getByText } = renderComponent({ theme: themeLight, name: 'Maggie' });
await waitForElement(() => getByText(/hello Maggie/i));
});
// Hoist helper functions (but not vars) to reuse between test cases
const renderComponent = ({ theme, name }) =>
  render(
    <ThemeProvider theme={theme}>
      <HelloMessageStyled name={name} />
    </ThemeProvider>
  );

it('renders greeting', async () => {
  // Render new instance in every test to prevent leaking state
  const { getByText } = renderComponent({ theme: themeLight, name: 'Maggie' });

  await waitForElement(() => getByText(/hello Maggie/i));
});