unit-test-vue-pinia
Write and review unit tests for Vue 3 + TypeScript + Vitest + Pinia codebases. Use when creating or updating tests for components, composables, and stores; mocking Pinia with createTestingPinia; applying Vue Test Utils patterns; and enforcing black-box assertions over implementation details.
- License 许可
- MIT
- 最近更新
- 2026-11-11
- Stars
- ★ 4.1w
- Forks
- 5.3k
01 前言 Front Matter
- name
- unit-test-vue-pinia
- category
- testing
- description
- Write and review unit tests for Vue 3 + TypeScript + Vitest + Pinia codebases. Use when creating or updating tests for components, composables, and stores; mocking Pinia with createTestingPinia; applying Vue Test Utils patterns; and enforcing black-box assertions over implementation details.
02 资源文件 8
- 参考文档references/advanced.md13.7 KB
- 参考文档references/alignment.md8.7 KB
- 参考文档references/blast.md12.4 KB
- 参考文档references/databases.md11.2 KB
- 参考文档references/phylogenetics.md13.5 KB
- 参考文档references/pinia-patterns.md1.8 KB
- 参考文档references/sequence_io.md7.1 KB
- 参考文档references/structure.md12.7 KB
03 SKILL.md 正文
unit-test-vue-pinia
Use this skill to create or review unit tests for Vue components, composables, and Pinia stores. Keep tests small, deterministic, and behavior-first.
Workflow
- Identify the behavior boundary first: component UI behavior, composable behavior, or store behavior.
- Choose the narrowest test style that can prove that behavior.
- Set up Pinia with the least powerful option that still covers the scenario.
- Drive the test through public inputs such as props, form updates, button clicks, emitted child events, and store APIs.
- Assert observable outputs and side effects before considering any instance-level assertion.
- Return or review tests with clear behavior-oriented names and note any remaining coverage gaps.
Core Rules
- Test one behavior per test.
- Assert observable input/output behavior first (rendered text, emitted events, callback calls, store state changes).
- Avoid implementation-coupled assertions.
- Access
wrapper.vmonly in exceptional cases when there is no reasonable DOM, prop, emit, or store-level assertion. - Prefer explicit setup in
beforeEach()and reset mocks every test. - Use checked-in reference material in
references/pinia-patterns.mdas the local source of truth for standard Pinia test setups.
Pinia Testing Approach
Use references/pinia-patterns.md first, then fall back to Pinia's testing cookbook when the checked-in examples do not cover the case.
Default pattern for component tests
Use createTestingPinia as a global plugin while mounting.
Prefer createSpy: vi.fn as the default for consistency and easier action-spy assertions.
const wrapper = mount(ComponentUnderTest, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn,
}),
],
},
});
By default, actions are stubbed and spied.
Use stubActions: true (default) when the test only needs to verify whether an action was called (or not called).
Accepted minimal Pinia setups
The following are also valid and should not be flagged as incorrect:
createTestingPinia({})when the test does not assert Pinia action spy behavior.createTestingPinia({ initialState: ... })orcreateTestingPinia({ stubActions: ... })withoutcreateSpy, when the test only needs state seeding or action stubbing behavior and does not inspect generated spies.setActivePinia(createTestingPinia(...))in store/composable-focused tests (without mounting a component) when mocking/seeding dependent stores is needed.
Use createSpy: vi.fn when action spy assertions are part of the test intent.
Execute real actions only when needed
Use stubActions: false only when the test must validate the action's real behavior and side effects. Do not switch it on by default for simple "was called" assertions.
const wrapper = mount(ComponentUnderTest, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn,
stubActions: false,
}),
],
},
});
Seed store state with initialState
const wrapper = mount(ComponentUnderTest, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn,
initialState: {
counter: { n: 20 },
user: { name: "Leia Organa" },
},
}),
],
},
});
Add Pinia plugins through createTestingPinia
const wrapper = mount(ComponentUnderTest, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn,
plugins: [myPiniaPlugin],
}),
],
},
});
Getter override pattern for edge cases
const pinia = createTestingPinia({ createSpy: vi.fn });
const store = useCounterStore(pinia);
store.double = 999;
// @ts-expect-error test-only reset of overridden getter
store.double = undefined;
Pure store unit tests
Prefer pure store tests with createPinia() when the goal is to validate store state transitions and action behavior without component rendering. Use createTestingPinia() only when you need stubbed dependent stores, seeded test doubles, or action spies.
beforeEach(() => {
setActivePinia(createPinia());
});
it("increments", () => {
const counter = useCounterStore();
counter.increment();
expect(counter.n).toBe(1);
});
Vue Test Utils Approach
Follow Vue Test Utils guidance: https://test-utils.vuejs.org/guide/
- Mount shallow by default for focused unit tests.
- Mount full component trees only when integration behavior is the subject.
- Drive behavior through props, user-like interactions, and emitted events.
- Prefer
findComponent(...).vm.$emit(...)for child stub events instead of touching parent internals. - Use
nextTickonly when updates are async. - Assert emitted events and payloads with
wrapper.emitted(...). - Access
wrapper.vmonly when no DOM assertion, emitted event assertion, prop assertion, or store-level assertion can express the behavior. Treat it as an exception and keep the assertion narrowly scoped.
Key Testing Snippets
Emit and assert payload:
await wrapper.find("button").trigger("click");
expect(wrapper.emitted("submit")?.[0]?.[0]).toBe("Mango Mission");
Update input and assert output:
await wrapper.find("input").setValue("Agent Violet");
await wrapper.find("form").trigger("submit");
expect(wrapper.emitted("save")?.[0]?.[0]).toBe("Agent Violet");
Test Writing Workflow
- Identify the behavior boundary to test.
- Build minimal fixture data (only fields needed by that behavior).
- Configure Pinia and required test doubles.
- Trigger behavior through public inputs.
- Assert public outputs and side effects.
- Refactor test names to describe behavior, not implementation.
Constraints and Safety
- Do not test private/internal implementation details.
- Do not overuse snapshots for dynamic UI behavior.
- Do not assert every field in large objects if only one behavior matters.
- Keep fake data deterministic; avoid random values.
- Do not claim a Pinia setup is wrong when it is one of the accepted minimal setups above.
- Do not rewrite working tests toward deeper mounting or real actions unless the behavior under test requires that extra surface area.
- Flag missing test coverage, brittle selectors, and implementation-coupled assertions explicitly during review.
Output Contract
- For
createorupdate, return the finished test code plus a short note describing the selected Pinia strategy. - For
review, return concrete findings first, then missing coverage or brittleness risks. - When the safest choice is ambiguous, state the assumption that drove the chosen test setup.
References
references/pinia-patterns.md- Pinia testing cookbook: https://pinia.vuejs.org/cookbook/testing.html
- Vue Test Utils guide: https://test-utils.vuejs.org/guide/
04 同仓库更多 Skills
supabase-rls-policies
Write, review, and test Supabase Row Level Security (RLS) policies so that one user cannot read or change another user's rows. Use when creating or changing tables, policies, views, or security definer functions in a Supabase project, when reviewing a migration that touches RLS, or when asked to prove user isolation with pgTAP tests that sign in as two users.
skill-distribution-audit
Audit a skill collection before release or investigate installer omissions, archived/template leakage, duplicate identities, and manifest drift. Reconcile the intended public source set, distribution manifest, and actual discovery output for a specified consumer version. Includes a deterministic set-comparison helper.
logicapps-custom-code-net10-migration
Migrate Azure Logic Apps Standard local-function custom-code projects from .NET 8 to .NET 10. Use for legacy Logic Apps custom-code workspace upgrades, project/package configuration, custom-worker settings, publication, and integrated VS Code debugging. Not for ordinary .NET applications, standalone Azure Functions, Consumption workflows, or cloud deployment.
winmd-api-search
Find and explore Windows desktop APIs. Use when building features that need platform capabilities — camera, file access, notifications, UI controls, AI/ML, sensors, networking, etc. Discovers the right API for a task and retrieves full type details (methods, properties, events, enumeration values).
resemble-detect
Deepfake detection and media safety — detect AI-generated audio, images, video, and text, trace synthesis sources, apply watermarks, verify speaker identity, and analyze media intelligence using Resemble AI
quality-playbook
Run a complete quality engineering audit on any codebase. Derives behavioral requirements from the code, generates spec-traced functional tests, runs a three-pass code review with regression tests, executes a multi-model spec audit (Council of Three), and produces a consolidated bug report with TDD-verified patches. Finds the 35% of real defects that structural code review alone cannot catch. Works with any language. Trigger on 'quality playbook', 'spec audit', 'Council of Three', 'fitness-to-purpose', or 'coverage theater'.