Skip to content
Back to skills

React Testing

ASecurity

Write and review React/TypeScript tests for Sentry's frontend using Jest and React Testing Library. Use when adding or editing tests in static/ (*.spec.tsx), writing component/hook tests, mocking API responses with MockApiClient, testing routing or network requests, or when asked to "write a frontend test", "add a React test", "test this component", or "fix a flaky RTL test".

  • 45,908 stars
  • 0 votes
  • 1 copy
  • 10 views
  • Added September 1, 2026
devopstypescriptgoreacttestingapifrontend

Works with

  • cli
  • api

Security analysis

A100/100

Scanned December 1, 2026

npx -y skills add getsentry/sentry --skill react-testing --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of React Testing?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for React Testing
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/getsentry-react-testing/badge)](https://www.skillsdirectory.com/skills/getsentry-react-testing)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: react-testing
description: Write and review React/TypeScript tests for Sentry's frontend using Jest and React Testing Library. Use when adding or editing tests in static/ (*.spec.tsx), writing component/hook tests, mocking API responses with MockApiClient, testing routing or network requests, or when asked to "write a frontend test", "add a React test", "test this component", or "fix a flaky RTL test".
---

# React Testing Guidelines

## Testing Philosophy

- **Test user workflows**: Set up preconditions with fixtures, props, router state, and `MockApiClient`. Drive the behavior under test with `userEvent` clicks, typing, and keyboard navigation, then assert what the user sees or can do afterward, rather than component state, internal calls, or render counts.
- **Make assertions specific**: Name tests after the behavior they protect. Assert the expected content, validation message, destination, or submitted value; avoid vague checks such as “renders correctly” or “an error exists.”
- **Cover relevant failures**: Alongside successful behavior, cover validation failures, rejected requests, or permission restrictions when the changed behavior depends on them. Verify the specific feedback and recovery path where supported.
- **Choose coverage by what can regress**: Use RTL for user behavior and accessibility; use visual snapshots for appearance. Apply the selection rules below before adding assertions.
- **Keep tests independent**: Set up each test's fixtures, API responses, and store state explicitly. Clean up mutable state using the existing test helpers; never rely on test execution order. Prefer deterministic fixture overrides to random data unless uniqueness is part of the behavior under test.

## Choose RTL or Visual Snapshots Before Writing Tests

- Use RTL in `*.spec.tsx` for interactions, validation, submitted values, routing, network effects, and accessible names, roles, or states. Assert the observable outcome.
- Use unit tests for pure calculations or data transformations.
- Do not add RTL assertions using `toHaveStyle`, `toHaveStyleRule`, computed styles, CSS class names, or DOM structure solely to verify appearance. Do not mock a child component to inspect the styling props passed to it.
- Cover colors, typography, spacing, alignment, dimensions, responsive layout, and visual variants in colocated `*.snapshots.tsx` files with the repository's `it.snapshot` / `it.snapshot.each` API, not Jest DOM snapshots (`toMatchSnapshot` / `toMatchInlineSnapshot`). Use the **`generate-snapshot-tests`** skill for themes, variants, and container widths.
- Visual snapshots render with `renderToString`, so they have no `document`, effects, or API responses. If the styled element only appears after fetching data or running effects, snapshot the presentational component that renders it with props. If no such component exists, extract one or note in the PR that the change has no automated visual coverage. Do not fall back to appearance assertions in RTL.
- Distinguish CSS constraints from behavior: `min-width` / `max-width` belong in visual snapshots; an input's numeric limits need RTL coverage of validation or clamping after user input.
- For mixed changes, snapshot appearance and test behavior separately. For a disabled button, snapshot its appearance and use RTL to verify it cannot trigger an action. Do not duplicate its CSS in RTL.
- Before finishing, review each new assertion: replace appearance-only RTL checks with visual cases. Do not add an RTL smoke test merely to accompany a styling change.

## Imports

**Always** import from `sentry-test/reactTestingLibrary`, not directly from `@testing-library/react`:

```tsx
import {
  render,
  screen,
  userEvent,
  waitFor,
  within,
} from 'sentry-test/reactTestingLibrary';
```

## Query Priority (in order of preference)

1. **`getByRole`** - Primary selector for most elements

   ```tsx
   screen.getByRole('button', {name: 'Save'});
   screen.getByRole('textbox', {name: 'Search'});
   ```

2. **`getByLabelText`/`getByPlaceholderText`** - For form elements

   ```tsx
   screen.getByLabelText('Email Address');
   screen.getByPlaceholderText('Enter Search Term');
   ```

3. **`getByText`** - For non-interactive elements

   ```tsx
   screen.getByText('Error Message');
   ```

4. **`getByTestId`** - Last resort only
   ```tsx
   screen.getByTestId('custom-component');
   ```

## Best Practices

### Assert the outcome of the interaction

Use the real component and its providers with `MockApiClient` responses. When a request payload is part of the behavior, assert it as well as the resulting UI; a request being called alone does not prove the workflow succeeded.

```tsx
// ❌ A generic error check does not establish which failure was handled
expect(screen.getByRole('alert')).toBeInTheDocument();

// ✅ After submitting invalid input, check the specific validation feedback
await userEvent.clear(screen.getByRole('textbox', {name: 'Name'}));
await userEvent.click(screen.getByRole('button', {name: 'Save'}));
expect(await screen.findByText('Name is required')).toBeInTheDocument();
```

For a successful save, assert the saved content or destination. For a rejected request, configure its error response with `MockApiClient` and assert the specific error feedback; if retry is supported, exercise it and verify success.

### Avoid mocking hooks, functions, or components

Do not use `jest.mocked()`.

```tsx
// ❌ Don't mock hooks
jest.mocked(useDataFetchingHook)

// ✅ Set the response data
MockApiClient.addMockResponse({
    url: '/data/',
    body: DataFixture(),
})

// ❌ Don't mock contexts
jest.mocked(useOrganization)

// ✅ Use the provided organization config on render()
render(<Component />, {organization: OrganizationFixture({...})})

// ❌ Don't mock router hooks
jest.mocked(useLocation)

// ✅ Use the provided router config
render(<TestComponent />, {
  initialRouterConfig: {
    location: {
      pathname: "/foo/",
    },
  },
});

// ❌ Don't mock page filters hook
jest.mocked(usePageFilters)

// ✅ Update the corresponding data store with your data
PageFiltersStore.onInitializeUrlState(
    PageFiltersFixture({ projects: [1]}),
)

// ❌ Don't recreate the basic context providers
renderHook(useNavigate, {
  wrapper: (children) => (<AllTheProviders>{children}</AllTheProviders>),
})

// ✅ Use the provided helpers that mock everything
renderHookWithProviders(useNavigate)
```

### Use fixtures

Sentry fixtures are located in tests/js/fixtures/ while GetSentry fixtures are located in tests/js/getsentry-test/fixtures/.

```tsx

// ❌ Don't import type and initialize it
import type {Project} from 'sentry/types/project';
const project: Project = {...}

// ✅ Import a fixture instead
import {ProjectFixture} from 'sentry-fixture/project';

const project = ProjectFixture(partialProject)

```

### Call `render()` directly, not a `renderFoo()` helper

A local helper hides the JSX and `render()` options from every test that calls
it, and `rerender` takes an element, so the call site can no longer control
what renders. Repeating the JSX in each test is fine: the reader sees exactly
what each test renders.

```tsx
// ❌ Don't wrap render() in a helper
function renderWidget(project = ProjectFixture()) {
  return render(<Widget organization={organization} project={project} />, {organization});
}
renderWidget(project);

// ✅ Call render() in each test
render(<Widget organization={organization} project={project} />, {organization});
```

When the fixed JSX is large, such as many props, put the common props in an
object and spread them in each `render()` call:

```tsx
const commonProps = {organization, project, isLast: true, onClickSetupLater: jest.fn()};

render(<Widget {...commonProps} />, {organization});
render(<Widget {...commonProps} isLoading />, {organization});
```

Helpers that only register mocks, or that take the element as a parameter, are
fine.

### Use `screen` instead of destructuring

```tsx
// ❌ Don't do this
const {getByRole} = render(<Component />);

// ✅ Do this
render(<Component />);
const button = screen.getByRole('button');
```

### Query selection guidelines

- Use `getBy...` for elements that should exist
- Use `queryBy...` ONLY when checking for non-existence
- Use `await findBy...` when waiting for elements to appear

```tsx
// ❌ Wrong
expect(screen.queryByRole('alert')).toBeInTheDocument();

// ✅ Correct
expect(screen.getByRole('alert')).toBeInTheDocument();
expect(screen.queryByRole('button')).not.toBeInTheDocument();
```

### Async testing

```tsx
// ❌ Don't use waitFor for appearance
await waitFor(() => {
  expect(screen.getByRole('alert')).toBeInTheDocument();
});

// ✅ Use findBy for appearance
expect(await screen.findByRole('alert')).toBeInTheDocument();

// ✅ Use waitForElementToBeRemoved for disappearance
await waitForElementToBeRemoved(() => screen.getByRole('alert'));
```

### Avoid waiting for loading indicators

Do not use `findBy` with `.not.toBeInTheDocument()` for loading indicators. `findBy` will error if the element is not found, but we're asserting it should NOT exist. Loading indicators are also flakey since they appear on screen for only a few ticks.

```tsx
// ❌ Wrong - findBy errors if element not found, and loading indicators are flakey
expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();

// ✅ Correct - wait for the actual content you care about
await waitFor(() => {
  expect(screen.getByRole('button', {name: 'Submit'})).toBeInTheDocument();
});

// ✅ Also correct - use findBy on the content that appears after loading
expect(await screen.findByRole('button', {name: 'Submit'})).toBeInTheDocument();
```

### User interactions

```tsx
// ❌ Don't use fireEvent
fireEvent.change(input, {target: {value: 'text'}});

// ✅ Use userEvent
await userEvent.click(input);
await userEvent.keyboard('text');
```

### Testing routing

```tsx
const {router} = render(<TestComponent />, {
  initialRouterConfig: {location: {pathname: '/foo/', query: {page: '1'}}},
});
// Uses passes in config to set initial location
expect(router.location.pathname).toBe('/foo');
expect(router.location.query.page).toBe('1');
// Clicking links goes to the correct location
await userEvent.click(screen.getByRole('link', {name: 'Go to /bar/'}));
// Can check current route on the returned router
expect(router.location.pathname).toBe('/bar/');
// Can test manual route changes with router.navigate
router.navigate('/new/path/');
router.navigate(-1); // Simulates clicking the back button
```

If the component uses `useParams()`, the `route` property can be used:

```tsx
function TestComponent() {
  const {id} = useParams();
  return <div>{id}</div>;
}
const {router} = render(<TestComponent />, {
  initialRouterConfig: {location: {pathname: '/foo/123/'}, route: '/foo/:id/'},
});
expect(screen.getByText('123')).toBeInTheDocument();
```

### Testing components that make network requests

```tsx
// Simple GET request
MockApiClient.addMockResponse({url: '/projects/', body: [{id: 1, name: 'my project'}]});

// POST request
MockApiClient.addMockResponse({
  url: '/projects/',
  method: 'POST',
  body: {id: 1, name: 'my project'},
});

// Complex matching with query params and request body
MockApiClient.addMockResponse({
  url: '/projects/',
  method: 'POST',
  body: {id: 2, name: 'other'},
  match: [
    MockApiClient.matchQuery({param: '1'}),
    MockApiClient.matchData({name: 'other'}),
  ],
});

// Error responses
MockApiClient.addMockResponse({
  url: '/projects/',
  body: {detail: 'Internal Error'},
  statusCode: 500,
});
```

#### Always Await Async Assertions

Network requests are asynchronous. Always use `findBy` queries or properly await assertions:

```tsx
// ❌ Wrong - will fail intermittently
expect(screen.getByText('Loaded Data')).toBeInTheDocument();

// ✅ Correct - waits for element to appear
expect(await screen.findByText('Loaded Data')).toBeInTheDocument();
```

#### Handle Refetches in Mutations

When testing mutations that trigger data refetches, update mocks before the refetch occurs:

```tsx
it('adds item and updates list', async () => {
  // Initial empty state
  MockApiClient.addMockResponse({url: '/items/', body: []});

  const createRequest = MockApiClient.addMockResponse({
    url: '/items/',
    method: 'POST',
    body: {id: 1, name: 'New Item'},
  });

  render(<ItemList />);

  await userEvent.click(screen.getByRole('button', {name: 'Add Item'}));

  // CRITICAL: Override mock before refetch happens
  MockApiClient.addMockResponse({url: '/items/', body: [{id: 1, name: 'New Item'}]});

  await waitFor(() => expect(createRequest).toHaveBeenCalled());
  expect(await screen.findByText('New Item')).toBeInTheDocument();
});
```

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in devops →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.