Index of every page on this site: llms.txt
All skills
github avatar

/react18-enzyme-to-rtl

@f10fdb8 official
by githubgithub/awesome-copilot42k stars
5,426
Run it yourself

Provides exact Enzyme → React Testing Library migration patterns for React 18 upgrades. Use this skill whenever Enzyme tests need to be rewritten - shallow, mount, wrapper.find(), wrapper.simulate(), wrapper.prop(), wrapper.state(), wrapper.instance(), Enzyme configure/Adapter calls, or any test file that imports from enzyme. This skill covers the full API mapping and the philosophy shift from implementation testing to behavior testing. Always read this skill before rewriting Enzyme tests - do not translate Enzyme APIs 1:1, that produces brittle RTL tests.

Use this Skill: https://skilld.dev/gh/github/awesome-copilot/react18-enzyme-to-rtl

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesasync-patterns.md

≈1.9k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Async Test Patterns - Enzyme → RTL Migration

Reference for rewriting Enzyme async tests to React Testing Library with React 18 compatible patterns.

The Core Problem

Enzyme's async tests typically used one of these approaches:

  • wrapper.update() after state changes
  • setTimeout / Promise.resolve() to flush microtasks
  • setImmediate to flush async queues
  • Direct instance method calls followed by wrapper.update()

None of these work in RTL. RTL provides waitFor, findBy*, and act instead.


Pattern 1 - wrapper.update() After State Change

Enzyme required wrapper.update() to force a re-render after async state changes.

// Enzyme:
it('loads data', async () => {
  const wrapper = mount(<UserList />);
  await Promise.resolve(); // flush microtasks
  wrapper.update();        // force Enzyme to sync with DOM
  expect(wrapper.find('li')).toHaveLength(3);
});
// RTL - waitFor handles re-renders automatically:
import { render, screen, waitFor } from '@testing-library/react';

it('loads data', async () => {
  render(<UserList />);
  await waitFor(() => {
    expect(screen.getAllByRole('listitem')).toHaveLength(3);
  });
});

Pattern 2 - Async Action Triggered by User Interaction

// Enzyme:
it('fetches user on button click', async () => {
  const wrapper = mount(<UserCard />);
  wrapper.find('button').simulate('click');
  await new Promise(resolve => setTimeout(resolve, 0));
  wrapper.update();
  expect(wrapper.find('.user-name').text()).toBe('John Doe');
});
// RTL:
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

it('fetches user on button click', async () => {
  render(<UserCard />);
  await userEvent.setup().click(screen.getByRole('button', { name: /load/i }));
  // findBy* auto-waits up to 1000ms (configurable)
  expect(await screen.findByText('John Doe')).toBeInTheDocument();
});

Pattern 3 - Loading State Assertion

// Enzyme - asserted loading state synchronously then final state after flush:
it('shows loading then result', async () => {
  const wrapper = mount(<SearchResults query="react" />);
  expect(wrapper.find('.spinner').exists()).toBe(true);
  await new Promise(resolve => setTimeout(resolve, 100));
  wrapper.update();
  expect(wrapper.find('.spinner').exists()).toBe(false);
  expect(wrapper.find('.result')).toHaveLength(5);
});
// RTL:
it('shows loading then result', async () => {
  render(<SearchResults query="react" />);
  // Loading state - check it appears
  expect(screen.getByRole('progressbar')).toBeInTheDocument();
  // Or if loading is text:
  expect(screen.getByText(/loading/i)).toBeInTheDocument();

  // Wait for results to appear (loading disappears, results show)
  await waitFor(() => {
    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
  });
  expect(screen.getAllByRole('listitem')).toHaveLength(5);
});

Pattern 4 - Apollo MockedProvider Async Tests

// Enzyme with Apollo - used to flush with multiple ticks:
it('renders user from query', async () => {
  const wrapper = mount(
    <MockedProvider mocks={mocks} addTypename={false}>
      <UserProfile id="1" />
    </MockedProvider>
  );
  await new Promise(resolve => setTimeout(resolve, 0)); // flush Apollo queue
  wrapper.update();
  expect(wrapper.find('.username').text()).toBe('Alice');
});
// RTL with Apollo:
import { render, screen, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing';

it('renders user from query', async () => {
  render(
    <MockedProvider mocks={mocks} addTypename={false}>
      <UserProfile id="1" />
    </MockedProvider>
  );

  // Wait for Apollo to resolve the query
  expect(await screen.findByText('Alice')).toBeInTheDocument();
  // OR:
  await waitFor(() => {
    expect(screen.getByText('Alice')).toBeInTheDocument();
  });
});

Apollo loading state in RTL:

it('shows loading then data', async () => {
  render(
    <MockedProvider mocks={mocks} addTypename={false}>
      <UserProfile id="1" />
    </MockedProvider>
  );
  // Apollo loading state - check immediately after render
  expect(screen.getByText(/loading/i)).toBeInTheDocument();
  // Then wait for data
  expect(await screen.findByText('Alice')).toBeInTheDocument();
});

Pattern 5 - Error State from Async Operation

// Enzyme:
it('shows error on failed fetch', async () => {
  server.use(rest.get('/api/user', (req, res, ctx) => res(ctx.status(500))));
  const wrapper = mount(<UserCard />);
  wrapper.find('button').simulate('click');
  await new Promise(resolve => setTimeout(resolve, 0));
  wrapper.update();
  expect(wrapper.find('.error-message').text()).toContain('Something went wrong');
});
// RTL:
it('shows error on failed fetch', async () => {
  // (assuming MSW or jest.mock for fetch)
  render(<UserCard />);
  await userEvent.setup().click(screen.getByRole('button', { name: /load/i }));
  expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();
});

Pattern 6 - act() for Manual Async Control

When you need explicit control over async timing (rare with RTL but occasionally needed for class component tests):

// RTL with act() for fine-grained async control:
import { act } from 'react';

it('handles sequential state updates', async () => {
  render(<MultiStepForm />);

  await act(async () => {
    fireEvent.click(screen.getByRole('button', { name: /next/i }));
    await Promise.resolve(); // flush microtask queue
  });

  expect(screen.getByText('Step 2')).toBeInTheDocument();
});

RTL Async Query Guide

Method Behavior Use when
getBy* Synchronous - throws if not found Element is always present immediately
queryBy* Synchronous - returns null if not found Checking element does NOT exist
findBy* Async - waits up to 1000ms, rejects if not found Element appears asynchronously
getAllBy* Synchronous - throws if 0 found Multiple elements always present
queryAllBy* Synchronous - returns [] if none found Checking count or non-existence
findAllBy* Async - waits for elements to appear Multiple elements appear asynchronously
waitFor(fn) Retries fn until no error or timeout Custom assertion that needs polling
waitForElementToBeRemoved(el) Waits until element disappears Loading states, removals

Default timeout: 1000ms. Configure globally in jest.config.js:

// Increase timeout for slow CI environments
// jest.config.js
module.exports = {
  testEnvironmentOptions: {
    asyncUtilTimeout: 3000,
  },
};

Common Migration Mistakes

// WRONG - mixing async query with sync assertion:
const el = await screen.findByText('Result');
// el is already resolved here - findBy returns the element, not a promise
expect(await el).toBeInTheDocument(); // unnecessary second await

// CORRECT:
const el = await screen.findByText('Result');
expect(el).toBeInTheDocument();
// OR simply:
expect(await screen.findByText('Result')).toBeInTheDocument();
// WRONG - using getBy* for elements that appear asynchronously:
fireEvent.click(button);
expect(screen.getByText('Loaded!')).toBeInTheDocument(); // throws before data loads

// CORRECT:
fireEvent.click(button);
expect(await screen.findByText('Loaded!')).toBeInTheDocument(); // waits

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo4 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides comprehensive guidance for migrating React tests from Enzyme to React Testing Library. It contains only markdown documentation and code templates, posing no security risk.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at f10fdb8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated 7 months ago
  • React
  • Testing
  • enzyme
  • react-testing-library
  • migration
  • react18
  • unit-testing
  • jest

README badge

README badge for github/awesome-copilot/react18-enzyme-to-rtl

Rewrites Enzyme tests to React Testing Library for React 18, with API mappings and patterns that shift from asserting internal state to asserting visible behavior. Use this when migrating shallow/mount calls, wrapper.find(), simulate(), prop(), and state() checks to RTL equivalents.

Generated from the current SKILL.md.

Does this skill cover all Enzyme APIs?
Yes. It maps shallow, mount, find, simulate, prop, state, instance, and Enzyme configure/Adapter calls. Full before/after code is in the bundled references/enzyme-api-map.md and references/async-patterns.md.
Can I translate Enzyme tests 1:1 to RTL?
No. Enzyme tests implementation details (internal state, instance methods); RTL tests user-visible behavior. Tests asserting wrapper.state() or wrapper.instance() must be rewritten to assert visible outcomes instead.
Does this cover async patterns like waitFor and loading states?
Yes. The skill includes async-patterns.md with examples for waitFor, findBy, act(), Apollo MockedProvider, and error state testing.
What about wrapping components with providers (Apollo, Theme, etc.)?
The skill shows how to wrap with providers in RTL render calls and recommends using a project's customRender helper if available.

Generated from the current SKILL.md. These answers refresh after source changes.