# Write Vitest Tests for RTK Query and Redux Toolkit Slices

Yes. The agent finds the slices and API endpoints no test covers, mocks the network with MSW and tests loading, success and error states through the store.

[Run this on Rush](https://cloud.getrush.ai/run/write-vitest-tests/redux-toolkit/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts by listing what the existing tests exercise and, just as important, what they touch without checking. In a project like the official Vite template in reduxjs/redux-templates (`packages/vite-template-redux`, `@reduxjs/toolkit` `^2.12.0`, Vitest `^5.0.1`), nine tests exist: five in `src/App.test.tsx` and four in `src/features/counter/counterSlice.test.ts`. They cover the counter. Nothing covers `src/features/quotes`, where `quotesApiSlice.ts` defines an RTK Query API with `fetchBaseQuery` against `https://dummyjson.com/quotes` and `Quotes.tsx` renders three states: Loading, an error heading, and a list with a select for 5, 10, 20 or 30 quotes.

It then finds the hidden dependency. `App` renders `Quotes`, so every one of the five App tests sends a real request to `https://dummyjson.com/quotes?limit=10` and none of them waits for it or asserts on it. The suite passes whether that host answers or not, which means it proves nothing about quotes, and it calls a third party on every CI run. The agent confirms this by wrapping `fetch` in a scratch setup file and counting calls, then removes the scratch file.

The fix and the new tests share one piece: a mock server. The agent adds `msw`, starts `setupServer` from `msw/node` in `src/setupTests.ts` with a handler for the quotes URL that reads `limit` and returns that many quotes in the API's shape, resets handlers after each test and closes the server at the end. Unhandled requests are set to fail, so a new endpoint added without a handler shows up as a red test and not as a silent call to the internet. One detail depends on the version installed. In MSW 3, current when this page was written, that option is `onUnhandledFrame`. The MSW 2 name, `onUnhandledRequest`, is no longer on the option's type: the tests still pass with it and only `tsc` objects, so the agent confirms the name with the type check.

The tests go through the template's own helper. `renderWithProviders` in `src/utils/test-utils.tsx` builds a fresh store with `makeStore` for each render, so the RTK Query cache starts empty in every test and nothing has to be reset by hand. One test renders `Quotes`, sees Loading, then ten `blockquote` elements. One changes the select to 5 with the `user` the helper returns and asserts both the five quotes and that the handler saw `limit=5`. One overrides the handler with a 500 through `server.use` and expects the error heading. A fourth dispatches `quotesApiSlice.endpoints.getQuotes.initiate(10)` on a bare store and unwraps the result, which pins the endpoint without React. The agent finishes with `npm test`, `npm run type-check` and `npm run lint`, since Vitest transpiles test files without type-checking them.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Write the missing Vitest tests for the Redux Toolkit code in this repository. Read package.json, the Vitest config, the test setup file, the store, every slice and RTK Query API slice, the components that use them, the existing tests and the test helper that renders with a store first. Install dependencies and record the test, type check and lint results before changing anything. List which slices, thunks, selectors and API endpoints have no test. Find out whether the existing tests make real network requests, by counting fetch calls during a run, and report the URLs. Add msw as a dev dependency and start one mock server in the shared test setup, with handlers for every external URL the app calls, handlers reset after each test, and unhandled requests treated as errors; use the option name the installed msw version defines and confirm it with the type check. For each untested RTK Query endpoint add tests through the existing render helper for the loading state, a successful response, a changed argument that triggers a new request, and a failed response, plus one test that dispatches the endpoint's initiate action on a store without React. For each untested slice add reducer and selector tests. Use a fresh store per test and do not share cache between tests. Do not change application code; if a component cannot be tested as written, say why. Run the tests three times to check for flakiness, then the type check and lint. Open a pull request listing what was untested, the tests added and the output of each command.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that adds a test file beside the API slice, a few lines to the test setup, and `msw` to `devDependencies`. No file under `src/features` other than tests changes. The description starts with the inventory: each slice and endpoint, whether a test covered it before, and which new test covers it now.

It reports the network finding in plain terms: how many requests the suite sent to which host before, and that it sends none after, with unhandled requests failing the run. Then come the outputs of `npm test`, `npm run type-check` and `npm run lint`, and a note that the tests were run three times with the same result.

A reviewer reads the handlers first. They are the contract the tests hold the app to, so the fields and status codes in them should match what the real API returns; a handler that is more generous than the API makes every test above it meaningless. The reviewer also checks that the failure test asserts on what a user would see, the error heading, and not on internal state.

## Run it on every pull request that adds a slice

Create an automation in the Project that has the repository, with this prompt and a `github` trigger on `pull_request.opened`, narrowed with `branch_patterns` to your main branch. The event is added after the prompt as data, so write the prompt to say that the pull request named there is the one to read and that tests are wanted only for slices and endpoints it adds. Only pull requests from an owner, member or collaborator fire the trigger; forks and bots do not.

The automation's max runs per hour bounds how many start, and a pull request past it waits as a queued run. For a backlog instead of a stream, a script can send this body to `POST /o/{org}/sessions` once per feature folder with a `request_id` that is a UUID v5 of the repository and folder, so a retry returns the run that already exists.

## Why run it on Rush?

The finding that matters here, tests that call a live API without anyone noticing, cannot be read off the code with confidence; it has to be measured by running the suite and counting requests. In its own sandbox the agent does exactly that, and afterwards runs the suite with unhandled requests failing to show the count is zero. The commands and their output are kept in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Test writing is also work that parallelises. Each feature folder can be its own run on its own checkout, and each returns a small pull request with its test output attached, so a team clears a backlog of untested slices without one developer's machine running the suite all day.

## Frequently asked questions

### Why MSW and not a mocked fetch or a mocked base query?

Because the code under test then runs unchanged: `fetchBaseQuery` builds a real request, the handler answers it, and RTK Query parses a real response. Mocking `fetch` by hand skips serialisation and headers, and mocking the base query skips the endpoint's `query` function, which is the part most likely to be wrong.

### Do I need to reset the RTK Query cache between tests?

Not when every test builds its own store, as the template's `renderWithProviders` does through `makeStore`. If your tests import one shared store, the agent adds a dispatch of `api.util.resetApiState()` after each test, or changes the helper to build a store per render and says which it chose.

### Does it test thunks made with createAsyncThunk as well?

Yes. It dispatches the thunk on a real store and asserts on the state after it settles and, where a component shows a pending state, on that too. In the template, `incrementAsync` is already exercised through the Add Async button in `App.test.tsx`, so the agent lists it as covered and does not duplicate it.

### Will the tests work with Jest instead of Vitest?

The tests themselves carry over, since Testing Library and MSW behave the same. What differs is setup: the globals, the setup file key in the config, and the environment Jest needs for `fetch`. Tell the agent which runner the repository uses and it reads that config instead.

## More Redux Toolkit jobs

- [Persist Redux Toolkit State Across Page Reloads](https://getrush.ai/run/add-state-persistence/redux-toolkit/)

## The same job on other stacks

- [Write Vitest Tests for a Shopify App's Webhooks and Actions](https://getrush.ai/run/write-vitest-tests/shopify-app/)
- [Write Vitest Tests for a SvelteKit App](https://getrush.ai/run/write-vitest-tests/sveltekit/)
- [Write Vitest Tests for a tRPC Router](https://getrush.ai/run/write-vitest-tests/trpc/)
- [Write Vitest Tests for a Turborepo Monorepo](https://getrush.ai/run/write-vitest-tests/turborepo/)
- [Write Vitest Tests for a Vite React App](https://getrush.ai/run/write-vitest-tests/vite-react/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
