首先我們可以把store傳遞給一個(gè)localVue, 而不是傳遞給基礎(chǔ)的Vue構(gòu)造函數(shù)标沪。 localVue是一個(gè)獨(dú)立作用域的Vue構(gòu)造函數(shù)哆键,我們可以對其進(jìn)行改動而不影響到全局的Vue構(gòu)造函數(shù)髓霞。
actions里面有異步的網(wǎng)絡(luò)請求卦睹,這里我們使用msw 來mock. 具體代碼如下:
import { shallowMount, createLocalVue } from "@vue/test-utils";
import Vuex from "vuex";
import UsePagination from "./UsePagination.vue";
import { rest } from "msw";
import { setupServer } from "msw/node";
import paginationModule from "@/store/modules/utils/pagination.js";
const localVue = createLocalVue();
localVue.use(Vuex);
describe("Pagination Store Actions Mock", () => {
const server = setupServer(
rest.get(
"/components/virtualmachines",
(req, res, ctx) => {
return res(
ctx.json({
items: [
{
_data: {
link: "/api/v1/components/virtualmachines/2333"
},
}
]
})
);
}
)
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
let store;
beforeEach(() => {
store = new Vuex.Store({
state: {
data: [],
info: {
length: 1
}
},
actions: paginationModule.actions,
mutations: paginationModule.mutations
});
});
test("", async () => {
const wrapper = shallowMount(UsePagination, { store, localVue });
await paginationModule.actions.pagination(store, {
url: "/components/virtualmachines",
limit: 2
});
expect(wrapper.vm.$store.state.data[0]._data.link).toBe(
"/api/v1/components/virtualmachines/2333"
);
});
});
具體也可以參考: https://vue-test-utils.vuejs.org/zh/guides/using-with-vuex.html
但是官網(wǎng)給的是mock方法跟我這里的是不一樣的,現(xiàn)在其實(shí)是比較建議使用msw方库,比直接使用jest里面提供的mock方法更加輕量級结序,更加優(yōu)化。