我目前正在开发一个Vue.js应用程序,使用Pinia作为状态管理库,并使用Vitest进行测试。我在我的一个Pinia商店中有一个操作,它调用API来获取项目数据,然后更新商店的状态。然而,当我试图编写Vitest单元测试来模拟这个API调用,然后检查存储的状态时,存储的状态似乎没有按预期更新。
这是我的Pinia商店:
import { defineStore } from 'pinia';
import axios from '@/utils/axios';
import Swal from 'sweetalert2';
export const useProjectStore = defineStore('project', {
state: () => ({
projects: []
}),
actions: {
async getAllProjects() {
this.loading = true;
try {
await axios.get('projects', {
timeout: 15000
}).then((response) => {
this.projects = response.data;
}).catch((err) => {
this.loading = false;
});
} catch (error) {
this.loading = false;
console.error(error);
}
this.loading = false;
},
persist: true,
});
这是我的Vitest单元测试:
import { describe, test, expect, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useProjectStore } from '@/stores/project'
import axios from 'axios'
describe('Projects', () => {
let store = null
beforeEach(() => {
setActivePinia(createPinia())
store = useProjectStore()
})
test('that projects is empty at the beginning', () => {
expect(store.projects).toEqual([])
})
test('that the projects is filled with 3 projects', async () => {
await store.getAllProjects()
expect(store.projects).toHaveLength(3)
})
})
当我运行此测试时,它失败,并显示以下消息:
Expected: 3, Received: 0
这表示Pinia存储中的项目数组没有使用模拟数据进行更新。我很困惑为什么会发生这种情况,因为我似乎在正确模拟API调用并相应地更新状态。有人知道为什么我的Pinia状态在这次Vitest单元测试中没有按预期更新吗?如有任何见解或解决方案,我们将不胜感激!