首先我们可以把store传递给一个localVue, 而不是传递给基础的Vue构造函数。 localVue是一个独立作用域的Vue构造函数,我们可以对其进行改动而不影响到全局的Vue构造函数。
actions里面有异步的网络请求,这里我们使用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
但是官网给的是mock方法跟我这里的是不一样的,现在其实是比较建议使用msw,比直接使用jest里面提供的mock方法更加轻量级,更加优化。
网友评论