我想使用Jest测试Vuex操作。我使用 vuex-module-decorators以类的方式编写了一个Vuex商店。我的店铺如下。
import { Action, Module, Mutation, VuexModule } from "vuex-module-decorators";
@Module({ name: "counter", namespaced: true })
export class Counter extends VuexModule {
private count: number = 0;
@Mutation
public increment(): void {
this.count++;
}
get getCount() {
return this.count;
}
@Action({})
public add2(): void {
this.increment();
this.increment();
}
}我的测试代码如下。“突变测试”和“获取器测试”起作用。但我不知道如何测试动作。我无法正确执行"add2“操作。有人知道如何测试动作吗?
import Vuex from "vuex";
import { Counter } from "@/store/modules/counter";
import { createLocalVue } from "@vue/test-utils";
const localVue = createLocalVue();
localVue.use(Vuex);
describe("Counter test", () => {
it("mutation test", () => {
const mockState = {
count: 0
};
Counter.mutations!.increment(mockState, {});
expect(mockState.count).toBe(1);
});
it("getter test", () => {
const mockState = {
count: 3
};
expect(Counter.getters!.getCount(mockState, null, null, null)).toBe(3);
});
it("action test", () => {
const mockState = {
count: 3
};
// IntelliJ show error message
// "Cannot invoke an expression whose type lacks a call signature. Type 'Action ' has no compatible call signatures."
Counter.actions!.add2();
expect(mockState.count).toBe(4);
});
});发布于 2021-04-01 00:19:23
尝试挂载存储并对其进行测试,而不是直接测试模块,如下所示:
const store = new Vuex.Store({
modules: {
counter: Counter
}
})
it('should foo', () => {
store.dispatch('counter/add2')
expect(store.state.counter.count).toBe(4);
})如下所示,避免在测试之间共享状态以使用stateFactory标志也很有用:
@Module({ stateFactory: true, namespaced: true })https://stackoverflow.com/questions/63970109
复制相似问题