Vue 3 + Pinia组件测试:如何验证基于Getter的渲染?
问题
在Vue 3应用中使用Vue Testing Library测试依赖Pinia getter渲染的组件时遇到困难,希望验证组件中联系人姓名是否正确渲染。
组件代码:
<div v-for="contact in store.getContacts()"> <p>{{contact.firstName}} {{ contact.lastName }}</p> </div>
测试代码(基于Vitest和@testing-library/vue):
import { cleanup, getByRole, render, screen } from "@testing-library/vue"; import { describe, it, vi, beforeEach, afterEach } from "vitest"; import MyComponent from "@/components/MyComponent.vue"; import { createTestingPinia } from "@pinia/testing"; describe("MyComponent.vue", () => { let getByText: any, getByRole: any; beforeEach(() => { ({ getByText } = render(MyComponent, { global: { plugins: [ createTestingPinia({ initialState: { contacts: [{firstName:"Bill",lastName:"Jones"},{firstName:"Peter",lastName:"Smith"}], }, stubActions: false, createSpy: vi.fn, }), ], }, })); }); afterEach(() => { cleanup(); }); it("should display the first name", () => { getByText("Bill Jones"); }); });
Pinia Store定义:
interface Student { "id": number; "firstName": string; "lastName": string; "house": string; "year": number; "class": string; } interface ContactState { contacts: Student[]; } export const useContactStore = defineStore({ id: "contact", state: ():ContactState => ({ contacts: [], }),
对应的getter:
getContacts: (state) => { return state.contacts; }
应用本身运行正常,但测试无法通过,已尝试设置Store初始状态,但getter似乎未生效,想知道是否需要mock getter或是Store初始化方式有误。
解决方案
问题出在initialState的结构上——你的Pinia Store的id是contact,所以初始状态需要嵌套在对应Store id的键下,而不是直接写contacts。
具体修改步骤:
- 调整
createTestingPinia的initialState结构,把contacts放在contact键内(对应Store的id):
createTestingPinia({ initialState: { contact: { // 这里对应store的id: "contact" contacts: [{firstName:"Bill",lastName:"Jones"},{firstName:"Peter",lastName:"Smith"}], }, }, stubActions: false, createSpy: vi.fn, }),
不需要mock getter,
@pinia/testing会自动处理真实的getter逻辑,只要初始状态正确,getter就能返回对应的数据。另外,推荐直接使用
screen.getByText替代解构的getByText,更符合Testing Library的最佳实践:
it("should display the first name", () => { screen.getByText("Bill Jones"); });
修改后组件就能正确获取到Store中的初始数据,测试即可通过。
内容的提问来源于stack exchange,提问作者user4094935
相关产品推荐
相关产品推荐

