ShortIQ

ShortIQ

AI

50 AI Prompts for Testing: Jest, Vitest, and Playwright

Developer-tested AI prompts for unit testing with Jest and Vitest, React component testing with Testing Library, API mocking, end-to-end testing with Playwright, and CI integration. Write better tests faster.

June 29, 2026ShortIQ Editorial Team

Why Testing Developers Benefit from AI Prompts

Writing tests is one of the highest-value tasks to delegate to AI because tests are highly structured, have clear input-output patterns, and follow predictable templates. A Jest test for a function that takes input and returns output is almost entirely boilerplate once you know the function signature. AI eliminates that boilerplate while letting you focus on which scenarios to cover.

The most common failure mode when using AI for tests is getting generic test stubs that do not match the actual function signature, props, or behavior of the code under test. The prompts in this guide solve that by requiring the source code to be included in the prompt. AI generates accurate tests when given the code, not just a description of it.

  • Generate unit tests for pure functions, classes, and async utilities with Jest or Vitest
  • Write React component tests with Testing Library and user-event
  • Mock API calls, modules, and timers correctly for isolated tests
  • Build Playwright E2E tests for login flows, form submissions, and navigation
  • Generate test coverage reports and identify untested code paths

Unit Testing with Jest and Vitest Prompts

Jest and Vitest share almost identical APIs — describe, it/test, expect, beforeEach, afterEach, vi.fn()/jest.fn(). Vitest is faster for Vite-based projects and supports native ESM without configuration. The prompts in this section work for both — just specify which one you are using so the import statements are correct.

The most effective unit test prompts include the full source code of the function under test, the list of scenarios to cover, and any external dependencies that need to be mocked. AI generates accurate assertions when it can read the actual return values and error conditions from the source.

text
Act as a Vitest and TypeScript testing expert.

Task:
Write Vitest unit tests for this utility function.

[paste your function here]

Test scenarios to cover:
1. Happy path: all valid inputs, verify the return value
2. Edge cases: empty input, null, undefined, zero, empty array
3. Error cases: inputs that should throw, verify the error message
4. Boundary values: minimum valid input, maximum valid input

For each test:
- Use describe block for the function name
- Use it() with a descriptive name starting with should
- Follow the Arrange, Act, Assert pattern with blank lines between stages
- Use expect().toEqual() for objects, toBe() for primitives

Use: Vitest, TypeScript — no external libraries needed

React Component Testing with Testing Library Prompts

React Testing Library tests components from the user perspective — it queries by visible text, roles, and labels rather than implementation details like class names or component structure. This makes tests resilient to refactoring and more representative of how real users interact with the UI.

The key to accurate component test prompts is including the full component source. Testing Library queries depend on the actual text, ARIA roles, and input labels in the rendered output — without the source, AI invents queries that do not match your component. Always paste the component before listing test scenarios.

text
Act as a React Testing Library and Vitest expert.

Task:
Write component tests for this React component.

Component source:
[paste your component here]

Test scenarios:
1. Renders the correct initial state (check text, inputs, buttons visible)
2. User interaction: fill input, click button, check result
3. Conditional rendering: what changes when a prop flips
4. Error state: when an async action fails, error message appears
5. Loading state: spinner/skeleton visible while loading is true
6. Accessible: check ARIA roles and labels are correct

Requirements:
- Use screen queries (getByRole, getByText, getByLabelText) — no getByTestId
- Use userEvent.setup() for all user interactions
- Mock async calls with vi.mock()
- Wrap async assertions in waitFor() where needed

Use: Vitest, React Testing Library, @testing-library/user-event

API Mocking and Module Mock Prompts

Mocking is the most complex part of unit and component testing. The pattern differs between mocking a module export, mocking a named export from a module, mocking the return value of an async function, and mocking a module that has both default and named exports. AI generates correct mock patterns when given the import statement from the source file.

These prompts cover vi.mock() for module-level mocking, vi.fn() for individual function mocks, vi.spyOn() for watching real implementations, and MSW (Mock Service Worker) for API-level HTTP mocking in component tests.

text
Act as a Vitest mocking expert.

Task:
Write the correct mocks for this test file.

The source file under test imports:
import { fetchUser } from '../services/user.service';
import { useRouter } from 'next/navigation';
import { trackEvent } from '../lib/analytics';

Mock requirements:
1. fetchUser: mock to return a user object on the first call,
   and throw an Error on the second call

2. useRouter: mock to return an object with push: vi.fn()
   so we can assert router.push was called with the correct path

3. trackEvent: mock to do nothing but let us assert it was called
   with specific arguments

Provide:
- The vi.mock() calls with correct factory functions
- How to access the mock functions inside test cases
- How to reset mocks between tests

Use: Vitest, TypeScript

End-to-End Testing with Playwright Prompts

Playwright is the leading E2E testing tool for web applications. It supports Chrome, Firefox, and WebKit, has a powerful locator API that prefers accessible queries over CSS selectors, and includes a codegen tool that records tests by watching your interactions in the browser.

These prompts generate Playwright tests for the most common user flows: login and authentication, form submission with validation, navigation between pages, and data table interactions. Include the URLs, form field labels, and success/error messages in the prompt for accurate locator generation.

text
Act as a Playwright E2E testing expert.

Task:
Write Playwright tests for a user registration and login flow.

App details:
- Registration page: /register
  Fields: Name (label: Full Name), Email, Password, Confirm Password
  Submit button text: Create Account
  Success: redirects to /dashboard with welcome message
  Error: shows inline error below the field

- Login page: /login
  Fields: Email, Password
  Submit button text: Sign In
  Success: redirects to /dashboard
  Error: shows alert message Invalid credentials

Tests needed:
1. Successful registration with valid data
2. Registration fails when passwords do not match
3. Registration fails when email is already in use
4. Successful login with valid credentials
5. Login fails with wrong password
6. Redirect to /login when accessing /dashboard without auth

Use: Playwright, TypeScript, getByRole and getByLabel locators (no CSS selectors)
Include: page fixture, baseURL from playwright.config.ts, beforeEach for setup

Test Coverage and CI Integration Prompts

Test coverage reports tell you which lines, branches, and functions are not tested. In Vitest, coverage is provided by v8 (fast, built-in) or Istanbul (more accurate branch coverage). In Jest, Istanbul is the default. These prompts generate coverage configuration, interpret coverage reports, and identify which untested code paths are most worth testing.

For CI integration, these prompts generate GitHub Actions workflows that run tests, collect coverage reports, enforce coverage thresholds, and fail the pipeline when coverage drops below the minimum. Specifying the threshold in the prompt avoids AI generating a coverage check without an enforcement step.

text
Act as a Vitest and GitHub Actions testing expert.

Task:
Set up test coverage enforcement in GitHub Actions.

Requirements:
1. vitest.config.ts: add coverage configuration
   - Provider: v8
   - Reporters: text (for terminal), json (for CI), html (for review)
   - Include: src/**/*.{ts,tsx}
   - Exclude: src/**/*.d.ts, src/**/types.ts, src/main.tsx
   - Thresholds: lines 80%, branches 70%, functions 80%, statements 80%
   - Fail build if thresholds are not met

2. GitHub Actions workflow:
   - Trigger: push to main and pull_request to main
   - Run: npm ci, npm run test:coverage
   - Upload coverage report as workflow artifact
   - Post coverage summary as a PR comment using coverage-report-action
   - Fail the workflow if Vitest exits with a non-zero code

3. package.json scripts needed: test, test:coverage, test:ui

Use: Vitest 2, v8 coverage, GitHub Actions

Debugging Failing Tests with AI Prompts

Failing tests produce specific error messages that AI can interpret accurately when given the full context: the error output, the test code, and the source code under test. Common failure patterns — mismatched mock return types, missing async awaits, wrong locator queries in Playwright — all have recognizable fingerprints that AI identifies quickly.

The debug prompt structure is simple: paste the failing test, the error message, and the relevant source code, then ask for the root cause and fix. AI is most useful for the class of failures where the error message is cryptic but the fix is a one-line change once you know what to look for.

text
Act as a Vitest and React Testing Library debugging expert.

Task:
Diagnose why this test is failing and provide the fix.

Error output:
[paste the full error message and stack trace here]

Failing test:
[paste the test code here]

Source code under test:
[paste the component or function being tested]

Mock setup (if any):
[paste vi.mock() calls and mock implementations]

Provide:
1. The root cause of the failure in plain language
2. The specific line(s) that need to change
3. The fixed test code
4. Why the fix works
5. Any related test improvements to prevent similar failures

Do not rewrite tests that are not broken — only fix what is failing.

FAQ

What is the best way to use AI for writing tests?

Always paste the source code of the function or component under test into the prompt. AI generates accurate assertions and correct mock patterns when it can read the actual implementation. Without the source, it invents test scenarios that do not match your real code signatures, return values, or error messages.

Should I use Jest or Vitest for a new project?

Use Vitest for any project that uses Vite — it shares the same config and is significantly faster. Use Jest for projects using Create React App, Next.js (which has its own Jest configuration), or any non-Vite build tool. Both have nearly identical APIs so switching between them requires minimal changes.

Can AI write Playwright tests from a description?

Yes, but include the actual page URLs, form field labels, button text, and success/error message text. Playwright locators are based on what is visible in the browser — without these details, AI invents text that does not match your UI. The prompt in Section 5 shows the information to include for accurate locator generation.

How do I prompt AI to mock an API call in Vitest?

Include the exact import statement from the file under test. AI needs the module path and the export name to generate the correct vi.mock() factory. Also specify what the mock should return, whether it should throw, and whether the mock needs to return different values on successive calls. The prompt in Section 4 covers all three patterns.

Can AI help improve test coverage?

Yes. Paste the coverage report (the text output from npm run test:coverage) and the source file it covers. Ask AI to identify which branches and functions are untested and suggest test cases for them. This is faster than reading the coverage HTML report manually to find the gaps.

What is the difference between unit, integration, and E2E tests?

Unit tests test a single function or component in isolation with all dependencies mocked. Integration tests test multiple units working together, often including a real database or API. E2E tests drive a real browser through real user flows against a running application. Jest and Vitest handle unit and integration tests; Playwright handles E2E tests.

How do I use AI to fix a failing test?

Paste the full error message, the failing test code, and the source code under test into the prompt. Ask for the root cause and the fix. AI identifies common failure patterns — missing awaits, wrong mock return types, incorrect locators — quickly when given the full error output rather than a description of the problem.

Can AI write snapshot tests?

Yes, but snapshot tests have limited value for most components — they break on any UI change and the diffs are hard to review. AI is more useful for generating behavior-based tests with explicit assertions. If you do need snapshot tests, ask AI to also generate a comment explaining what change would legitimately break the snapshot, so future developers know when to update it.

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.