# Write Vitest Tests for Pinia Stores

Yes. An agent adds Vitest and tests each Pinia store's state, getters and actions on a fresh pinia, plus one mounted component, and opens a pull request.

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

## What the agent does

The agent reads what the stores do and what already tests them. In a Vue 3 app like piniajs/example-vue-3-vite there are two stores. `src/stores/cart.ts` keeps `rawItems`, a getter `items` that folds repeated names into `{ name, amount }` rows, and three actions: `addItem`, `removeItem`, which removes the last occurrence with `lastIndexOf`, and `purchaseItems`, which calls `useUserStore()` and returns early when there is no user name. `src/stores/user.ts` starts with `name: 'Eduardo'` and `isAdmin: true`, and has `login` and `logout`. Nothing tests either directly. The `test` script is `cypress run`, and the one spec in `cypress/e2e/main.cy.js` types two items and clears the cart, so `removeItem`, `purchaseItems`, `login` and `logout` are run by no test.

Choosing packages is where a guess goes wrong, so the agent reads peer ranges from npm and versions from `yarn.lock`. The lock resolves Pinia 2.0.34, Vue 3.2.47 and Vite 8.0.0. Vitest 5.1.0 accepts Vite 8 and needs Node 22.12 or newer, and `.github/workflows/test.yml` runs Node 26. `@pinia/testing` is the one that bites: its latest release requires `pinia >=4.1.0`, and of the older ones, 0.0.16 is the release whose peer range starts at the locked 2.0.34. The agent pins that version and says why, adds `@vue/test-utils` and `happy-dom`, and writes a `vitest.config.ts` that merges `vite.config.ts` so the `@` alias and the Vue plugin are the same in tests as in the build. It adds a `test:unit` script and leaves `test` to Cypress.

Store tests use a real Pinia, created fresh in `beforeEach` with `setActivePinia(createPinia())`, so no state leaks between cases and the two stores talk to each other as they do in the app. The agent asserts behaviour, including the awkward parts. `purchaseItems` returns `this.items.length`, the number of distinct names: a cart of two apples and one pear reports 2. It logs through `console.log`, which the test spies on and silences. Called after `logout()` it returns `undefined` and leaves the cart as it was. `login('ed', 'ed')` makes an admin, any other name with the password `ed` signs in without admin, and a wrong password rejects with `invalid credentials` and leaves the state untouched. Each of these is written to what the code does today; the ones that look like bugs are listed for a maintainer, not changed.

One component test mounts `App.vue` through `@vue/test-utils`, with `createPinia()` in `global.plugins`, submits the add form and clicks Clear. That click calls `window.confirm`, and the two common DOM environments differ on it: under happy-dom 21 the function does not exist, so `vi.spyOn(window, 'confirm')` itself throws and the test uses `vi.stubGlobal`; under jsdom 31 it exists, prints a not-implemented notice and returns `undefined`, so the cart is silently not cleared. A second mount uses `createTestingPinia({ createSpy: vi.fn })` to show the other style, where actions are replaced by spies: the form calls `addItem` with the typed name and the list stays empty. The agent runs `yarn test:unit`, `yarn build` and the existing Cypress test, and adds a `yarn test:unit` step to the workflow.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Vitest unit tests for the Pinia stores in this Vue 3 app. Read package.json, yarn.lock (resolved pinia, vue, vite and typescript versions), vite.config.ts, both tsconfig files, src/main.ts, src/App.vue, src/layouts/default.vue, both stores under src/stores, cypress/e2e/main.cy.js and .github/workflows/test.yml first. Choose versions from npm peer ranges, not from memory: a vitest that accepts the locked vite and the workflow's Node version, @vue/test-utils, a DOM environment, and the newest @pinia/testing whose peer range accepts the locked pinia; state each choice and its range in the pull request. Add vitest.config.ts that merges vite.config.ts, and a test:unit script; leave the test script and the Cypress spec alone. Write store tests that create a fresh pinia in beforeEach and cover every getter and action in cart.ts and user.ts, including removeItem on a repeated and a missing name, purchaseItems with and without a user and what number it returns, login for each branch of apiLogin, and logout. Spy on console.log where a store logs. Add one component test that mounts App.vue with a real pinia, adds an item and clears the cart, handling window.confirm for the DOM environment you chose, and one that uses createTestingPinia to assert an action was called. Test what the code does today; list anything that looks like a bug in the pull request and do not change files under src other than adding tests. Run yarn test:unit, yarn build and the existing Cypress test, add a yarn test:unit step to .github/workflows/test.yml, paste the output and open a pull request.",
  "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 `vitest.config.ts`, a test file for each store, one for `App.vue`, four dev dependencies in `package.json` with their `yarn.lock` entries, the `test:unit` script and one step in `.github/workflows/test.yml`. No file under `src` changes other than the new tests. The description has a table of the packages added, the version chosen and the peer range that decided it, with the `@pinia/testing` row explaining why the latest release was not usable on this lockfile.

It pastes the output of `yarn test:unit`, `yarn build` and the Cypress run, and then lists what the tests pinned that a maintainer may want to change. `purchaseItems` counts distinct names, so the app's `Bought n items` message under-reports a cart with repeats. The user store starts signed in as an admin called Eduardo. `App.vue` assigns both stores to `window.stores`. And `yarn type-check` fails on the default branch, because the locked `vue-tsc` cannot load the locked TypeScript 7, so the new test files are transpiled by Vitest and not type-checked by anything.

A reviewer checks that the store tests assert results and not implementation: the rows `items` returns, the value an action resolves to, the state after it, and not the order of internal calls. They check that every test starts from a new Pinia and none depends on another having run. And they read the list of pinned oddities as a to-do: a test that documents `purchaseItems` returning 2 for three items is correct today and should be edited in the same commit that fixes the count.

## Run it on every pull request labelled store-tests

Stores gain actions one feature at a time, and the tests are easiest to write while the change is fresh. Add an automation to the Project that holds the repository with a `github` trigger on `pull_request.labeled` and `store-tests` in its `labels`, and a prompt that asks for Vitest tests of every getter and action the pull request adds or changes under `src/stores`, in the style of the existing store tests. The trigger places the pull request after the prompt and fills in nothing. It fires when an owner, member or collaborator applies the label, never for a fork or a bot, and the run opens its own pull request with the tests.

## Why run it on Rush?

Most of the time in this job goes to the setup nobody remembers: which helper release matches an old Pinia, why a spy on `confirm` throws in one DOM library and silently does nothing in another, why the testing helper refuses to start without a spy factory. Each is found by running the suite and reading the failure. The agent does that loop in its own sandbox on a fresh clone, so the versions it settles on are ones that installed and passed from nothing, and the same commands will behave the same in CI.

The run keeps its work. Every `yarn test:unit` invocation, including the failing ones on the way, is in the session's transcript at `GET /o/{org}/sessions/{id}/messages`, with the command in the event's `args` and the output in its result. When the description says the latest `@pinia/testing` could not be used, the peer range it read is there.

## Frequently asked questions

### Which @pinia/testing version works with Pinia 2?

It depends on the minor. When this page was written the latest release required `pinia >=4.1.0`, the 0.1 line needed 2.1.5 or newer, and 0.0.16 accepted 2.0.34 and up. The agent reads the peer range from npm for the Pinia version in your lockfile and pins the newest release that fits.

### Why does my test say createSpy must be configured?

`createTestingPinia` needs a function that makes spies. With Vitest globals on it finds `vi.fn` by itself; with them off, as in this project, pass `createTestingPinia({ createSpy: vi.fn })`.

### happy-dom or jsdom?

Either runs these tests. They differ on browser dialogs: happy-dom 21 has no `window.confirm`, so stub it with `vi.stubGlobal`, and jsdom 31 has one that returns `undefined` with a notice, so spy on it and return `true`. The agent picks one, says which, and handles its behaviour in the test.

## More Pinia jobs

- [Upgrade Pinia 2 to Pinia 4 in a Vue 3 App](https://getrush.ai/run/upgrade-pinia/pinia/)

## The same job on other stacks

- [Write Vitest Tests for React Router Loaders and Actions](https://getrush.ai/run/write-vitest-tests/react-router/)
- [Write Vitest Tests for RTK Query and Redux Toolkit Slices](https://getrush.ai/run/write-vitest-tests/redux-toolkit/)
- [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/)

## 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/)
