使用ViTest测试Pinia的store的示例

2022-08-14  本文已影响0人  JohnYuCN

1. src/stores/AlbumStore.ts

注意:要使用Axios库,保证可以在单元测试环境下可以使用。

import type Album from "@/model/Album";
import { defineStore } from "pinia";
import axios from 'axios'


const url = "http://johnyu.cn:3000/albums/";

export const useAlbumStore = defineStore({
  id: "albums",
  state: () => ({
    albums: new Array<Album>(),
    spotlight: <Album>{},
    current: <Album>{},
    updatorVisible: false,
  }),
  actions: {
    async findAllAlbums() {
      this.albums = await axios.get(url).then(resp => resp.data)
      return this.albums;
    },
    async loadAlbum(id: number | string) {
      this.spotlight = await axios.get(url + id).then(resp => resp.data)
      return this.spotlight;
    },
    async deleteAlbum(id: number) {
      const obj = await axios({ url: url + id, method: "DELETE" }).then(resp => resp.data)
      const index = this.albums.findIndex((item) => item.id === id);
      this.albums.splice(index, 1);
      return obj;
    },
    async addAlbum(album: Album) {
      const newAlbum = await axios({
        url, method: "POST", data: album
      }).then(resp => resp.data)
      this.albums.push(newAlbum);
      return newAlbum;
    },
    async updateAlbum() {
      const newAlbum = await axios({ url: url + this.current.id, method: "PUT", data: this.current }).then(resp => resp.data)
      const index = this.albums.findIndex((item) => item.id === newAlbum.id);
      this.albums.splice(index, 1, newAlbum);
      return newAlbum;
    },
  },
});

2. src/stores/tests/album.test.ts

import { assert, expect, test, describe, beforeAll, it } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'
import { useAlbumStore } from '../AlbumStore'
describe("测试pinia", () => {
    let store:any;
    beforeAll(() => {
        /**单元测试环境下,需要显式的激活pinia */
        setActivePinia(createPinia())
        store = useAlbumStore()
    })
    it("测试查询一条数据", async () => {
        await store.loadAlbum(1)
        expect(store.spotlight.name).toBe("勇气")
    })
    it("测试查询所有的数据", async () => {
        await store.findAllAlbums();
        expect(store.albums.length).gt(0)
    })
    
    it("添加一条数据", async () => {
        let album = { name: "tom", price: 45, area: "港台" }
        let na = await store.addAlbum(album)
        expect(na.id).toBeDefined()
    
    })
    it("更新一条数据", async () => {
        let alb = await store.loadAlbum(25)
        store.current = alb
        store.current.name = "tom1"
        let alb1 = await store.updateAlbum()
        expect(alb1.name).toBe("tom1")
    })
    
    
    it("删除一条数据", async () => {
        let obj = await store.deleteAlbum(51)
        assert.deepEqual(obj, {}, "xxx")
    })
})
上一篇下一篇

猜你喜欢

热点阅读