ShortIQ

ShortIQ

AI

50 AI Prompts for React Testing Library and Jest

50 AI prompts for testing React applications with Testing Library and Jest. Covers unit testing components, user interaction testing, mocking APIs and hooks, snapshot testing, integration tests, accessibility checks, and CI/CD setup.

June 19, 2026ShortIQ Editorial Team

How to Use These React Testing Prompts

React Testing Library encourages testing components the way users interact with them: finding elements by role, label, or text rather than by CSS class or internal implementation details. These 50 prompts cover the full testing workflow for React applications, from basic component rendering to complex async interactions, API mocking, and accessibility validation.

All prompts assume React 18, React Testing Library 14, and Jest 29 (or Vitest as a drop-in replacement). For best results, paste the component you want to test before each prompt and specify which behaviours you want to verify. Testing Library tests should read like a user interaction story, not like an implementation inspection.

Component Tests and User Interactions (Prompts 1-18)

Prompt 1: Write a React Testing Library test for a LoginForm component. The form has email and password inputs and a Submit button. Test that the form renders with empty inputs, that typing in each field updates its value, that submitting with empty fields shows validation error messages, and that a successful submit with valid credentials calls an onSubmit prop with the email and password values.

Prompt 2: Create a test for a controlled select dropdown component. Render the component with a list of options, verify the default option is selected, use userEvent.selectOptions to choose a different option, verify the onChange callback is called with the correct value, and verify the selected option is visually reflected in the component. Prompt 3: Write a test for a modal dialog component. Render the page with the modal closed, verify the modal content is not in the document (using queryByRole rather than getByRole to avoid the not found error), click the Open button, verify the modal is now visible, click the Close button or press Escape, and verify the modal is removed from the DOM.

  • Prompt 4: Create a test for a pagination component. Render a list with 25 items showing 10 per page. Verify page 1 shows items 1-10, click Next, verify page 2 shows items 11-20, click Previous, verify page 1 is shown again, and verify the Previous button is disabled on page 1 and the Next button is disabled on the last page.
  • Prompt 5: Write a test for a file upload input. Use userEvent.upload to simulate a file selection, verify the file name appears in the component after upload, verify the onChange callback is called with the File object, and test the error state when a file exceeds the maximum size limit.
  • Prompt 6: Create a test for a search input with debounced API calls. Mock the API function, type a search query character by character using userEvent.type, use jest.useFakeTimers to advance the debounce timer, verify the API was called only once with the full query (not on each keystroke), and verify the search results appear in the list.
  • Prompt 7: Write a test for a drag-and-drop sortable list using userEvent. Simulate dragging the first item to the third position using fireEvent.dragStart, fireEvent.dragOver, and fireEvent.drop. Verify the list order has changed correctly after the drop. Show how to query the list items by their text content to verify the new order.
  • Prompt 8: Create a test for a tabs component. Render the component with three tabs. Verify the first tab panel is visible and the others are hidden (aria-hidden or not in the DOM). Click the second tab, verify the second panel becomes visible. Verify tab keyboard navigation works: focus the first tab, press ArrowRight, verify the second tab receives focus.
  • Prompt 9: Write a test for a tooltip component. Render a button with an attached tooltip. Verify the tooltip is not visible by default. Hover over the button using userEvent.hover, verify the tooltip appears with the correct text. Move the mouse away using userEvent.unhover and verify the tooltip disappears.
  • Prompt 10: Create a test for a countdown timer component. Mock the timer using jest.useFakeTimers. Render the timer with a 10-second countdown. Advance time by 5 seconds using jest.advanceTimersByTime. Verify the display shows 5 seconds remaining. Advance to 0 and verify the onComplete callback is called.
  • Prompt 11: Write a test for a number input with increment and decrement buttons. Render with an initial value of 5 and min of 0 and max of 10. Click the increment button three times and verify the value reaches 8. Click the decrement button four times and verify it stops at 4 (not going below 0 if the initial were 4). Test that typing directly into the input also updates the value.
  • Prompt 12: Create a test for a multi-step form wizard. Render step 1, fill in the required fields, click Next, verify step 2 is shown and step 1 is hidden. Fill step 2, click Next, verify step 3. Click Back and verify step 2 is restored with the previously entered values. Submit on step 3 and verify the onSubmit prop receives all collected data.
  • Prompt 13: Write a test for a combobox autocomplete component. Focus the input, type a partial query, verify a dropdown list appears with filtered options, use ArrowDown to navigate to the second option, press Enter to select it, verify the input now shows the selected value and the dropdown closes.
  • Prompt 14: Create a test for an infinite scroll list. Mock the API for the first page, render the list, verify 10 items are shown. Scroll to the bottom by simulating an Intersection Observer callback (mock the IntersectionObserver), verify the API is called for page 2, verify 20 items are now shown.
  • Prompt 15: Write a test for a rich text editor component. Verify it renders with placeholder text when empty, that typing adds text content, that selecting text and clicking Bold wraps it in a bold element, and that the onChange callback receives the updated HTML content.
  • Prompt 16: Create a test for an image gallery with a lightbox. Render a grid of thumbnails, click the second thumbnail, verify the lightbox opens showing the full-size second image, click the Next arrow, verify the third image is shown, press Escape, and verify the lightbox closes.
  • Prompt 17: Write a test for a data table with sorting. Render a table with columns Name, Age, and Date. Click the Name column header and verify rows are sorted alphabetically. Click Name again and verify reverse alphabetical order. Click Age and verify numeric sorting.
  • Prompt 18: Create a test for a colour picker component. Render the picker with an initial colour value. Click a colour swatch and verify the onChange callback is called with the new hex value. Verify the preview box updates to show the selected colour. Test the hex input field accepts a manually typed hex code.

API Mocking, Hooks, Accessibility, and CI (Prompts 19-50)

Prompt 19: Write a React Testing Library test that mocks an API call using Mock Service Worker (MSW). Set up a test server handler that intercepts GET /api/users and returns a fixture array. Render a UserList component, verify a loading spinner is shown initially, wait for the users to appear using findByRole, and verify the correct user names are in the list.

Prompt 20: Create a test for an API error state using MSW. Configure the server to return a 500 error for the users endpoint. Render the UserList component, wait for the error message to appear, and verify the error text matches the expected message. Show how to override the server handler in a specific test while keeping the default handler for others. Prompt 21: Write a test for a custom React hook using renderHook. Test a useCounter hook that has increment, decrement, and reset actions. Use renderHook to mount the hook, use act to call the increment action, and verify the count state updates correctly.

  • Prompt 22: Create a test for a custom data-fetching hook using renderHook and MSW. Test a useUser(id) hook that returns loading, error, and data states. Mock the API, call the hook, verify the initial state shows loading: true, wait for the data to resolve, verify loading is false and data contains the user.
  • Prompt 23: Write accessibility tests using jest-axe. Render a form component and run await axe(container). Expect the result to have no violations. Then render a form with a missing label to verify axe catches the accessibility violation. Show how to configure axe rules and suppress false positives for specific components.
  • Prompt 24: Create a snapshot test for a Card component. Render the component with specific props, call toMatchSnapshot, and verify the snapshot is saved. Show how to update snapshots with jest --updateSnapshot. Explain when snapshot tests are useful (component library components with stable output) and when they are not (frequently changing components).
  • Prompt 25: Write a test that verifies focus management in a dialog. Open a modal dialog, verify the first focusable element inside the dialog receives focus automatically. Tab through all focusable elements and verify focus is trapped inside the modal. Close the modal and verify focus returns to the button that opened it.
  • Prompt 26: Create a test for a component that uses useContext. Wrap the component in a custom context provider with test values. Verify the component renders correctly using the context values. Test that a button click dispatches the correct context action and the UI updates accordingly.
  • Prompt 27: Write a Jest configuration for a Next.js project. Show jest.config.ts with the next/jest transform, moduleNameMapper for path aliases and CSS modules, testEnvironment set to jsdom, setupFilesAfterFramework pointing to a jest.setup.ts that imports @testing-library/jest-dom, and collectCoverageFrom to include all tsx and ts files.
  • Prompt 28: Create a GitHub Actions workflow that runs Jest tests. Run tests on every pull request, use the Node.js matrix to test on multiple versions, cache node_modules, run tests with coverage, and post the coverage percentage as a PR comment. Fail the workflow if coverage drops below 80%.

FAQ

What is the difference between React Testing Library and Enzyme?

React Testing Library (RTL) tests components from the user perspective: finding elements by role, label, and text as a user would. Enzyme tests implementation details: shallow rendering, component state, and internal methods. RTL is now the industry standard — tests written with RTL are more resilient to refactoring because they do not depend on internal implementation. Enzyme is no longer maintained for React 18. Use React Testing Library for all new projects.

Should I use Jest or Vitest for React testing?

Vitest for new projects using Vite (including Vite-based React, SvelteKit, Nuxt). Vitest is faster, has native ESM support, and shares configuration with Vite. Jest for Next.js projects and existing projects already using Jest. The API surface is nearly identical — the same React Testing Library queries, matchers, and patterns work in both. Migrating from Jest to Vitest is usually a one-hour configuration change.

How do I test components that make API calls?

Use Mock Service Worker (MSW). MSW intercepts network requests at the service worker or node level, not by mocking the fetch or axios module. This means your tests exercise the same code path as production (including the fetch call itself) and only the network response is mocked. Set up the MSW server in your jest.setup.ts, define handlers for your API endpoints, and reset handlers between tests. MSW is the recommended approach by the React Testing Library team.

What does findByRole wait for that getByRole does not?

getByRole is synchronous — it queries the current DOM immediately. findByRole is asynchronous — it retries the query until the element appears (default 1000ms timeout) or throws. Use getByRole for elements that are already in the DOM when the component renders. Use findByRole for elements that appear after an async operation (API call, timer, animation). Using getByRole on a not-yet-rendered element causes the test to fail immediately; findByRole waits for it to appear.

Related free tools

If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.

Continue Reading

Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.

Free newsletter

Get new guides in your inbox

We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.

No spam. Unsubscribe any time.

Was this article helpful?

Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.

We use this to improve tutorials, examples, and technical depth.