Mock Action
Mock Action是 Pinia 学习中的单个核心知识点,下面直接说明用法。
定义
Mock Action是 Pinia 使用中的一个独立知识点,核心作用是:使用vi.fn() mock Store action,掌握测试异步action与API调用。
语法
常用语法是在 Store 定义或组件调用处完成配置与使用。
JavaScript
export const useUserStore = defineStore('user', {
state: () => ({ profile: null }),
actions: {
async loadProfile() {
this.profile = await fetch('/api/profile').then(r => r.json())
}
}
})
示例
JavaScript
export const useUserStore = defineStore('user', {
state: () => ({ profile: null }),
actions: {
async loadProfile() {
this.profile = await fetch('/api/profile').then(r => r.json())
}
}
})
注意事项
每个测试用例应创建独立 Pinia 实例,避免状态互相污染。
要点总结
Mock Action只解决当前知识点对应的问题。- 优先使用 Pinia 官方 API,避免引入多余封装。
- 示例代码应保持 Store 简洁、职责清晰。
📝 发现内容有误?点击此处直接编辑