unit-test-vue-pinia

作者: github

為 Vue 3 + TypeScript + Vitest + Pinia 程式碼庫撰寫與審查單元測試。適用於建立或更新元件、組合式函式及狀態管理的測試時使用;…

npx skills add https://github.com/github/awesome-copilot --skill unit-test-vue-pinia

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

  1. Identify the behavior boundary first: component UI behavior, composable behavior, or store behavior.
  2. Choose the narrowest test style that can prove that behavior.
  3. Set up Pinia with the least powerful option that still covers the scenario.
  4. Drive the test through public inputs such as props, form updates, button clicks, emitted child events, and store APIs.
  5. Assert observable outputs and side effects before considering any instance-level assertion.
  6. 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.vm only 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.md as 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: ... }) or createTestingPinia({ stubActions: ... }) without createSpy, 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 nextTick only when updates are async.
  • Assert emitted events and payloads with wrapper.emitted(...).
  • Access wrapper.vm only 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

  1. Identify the behavior boundary to test.
  2. Build minimal fixture data (only fields needed by that behavior).
  3. Configure Pinia and required test doubles.
  4. Trigger behavior through public inputs.
  5. Assert public outputs and side effects.
  6. 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 create or update, 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

來自 github 的更多技能

console-rendering
github
在 Go 中使用基於結構體標籤的控制台渲染系統的說明
official
acquire-codebase-knowledge
github
當使用者明確要求對現有程式碼庫進行映射、文件化或入門引導時,使用此技能。觸發詞如「映射此程式碼庫」、「文件化…」等提示。
official
acreadiness-assess
github
Run the AgentRC readiness assessment on the current repository and produce a static HTML dashboard at reports/index.html. Wraps `npx github:microsoft/agentrc…
official
acreadiness-generate-instructions
github
透過 AgentRC 指令命令生成量身打造的 AI 代理指令檔案。產生 .github/copilot-instructions.md(預設,建議用於 VS Code 中的 Copilot…
official
acreadiness-policy
github
幫助使用者選取、撰寫或套用 AgentRC 政策。政策可透過停用不相關的檢查、覆寫影響/等級、設定…來自訂整備度評分。
official
add-educational-comments
github
為程式碼檔案添加教育性註解,將其轉化為有效的學習資源。根據三個可設定的知識層級(初學者、中級、進階)調整解釋深度與語氣。若未提供檔案,會自動請求提供,並以編號清單對應以便快速選取。僅透過教育性註解將檔案擴充最多125%(嚴格上限:400行新註解;超過1,000行的檔案上限為300行)。保留檔案編碼、縮排風格、語法正確性及……
official
adobe-illustrator-scripting
github
使用 ExtendScript (JavaScript/JSX) 編寫、除錯及最佳化 Adobe Illustrator 自動化腳本。適用於建立或修改操控…的腳本時。
official
agent-governance
github
宣告式政策、意圖分類與稽核軌跡,用於控制AI代理工具存取與行為。可組合的治理政策定義允許/封鎖的工具、內容過濾器、速率限制與核准要求——以配置而非程式碼形式儲存。語意意圖分類在工具執行前,透過基於模式的訊號偵測危險提示(資料外洩、權限提升、提示注入)。工具層級治理裝飾器在函式層級強制執行政策……
official