fanfanta
fanfanta

Reputation: 181

Q: Vuex-module-decorators: How to test a Vuex actions using jest?

I'd like to test Vuex actions using Jest. I use vuex-module-decorators to write a Vuex store in a class style. My store is as below.

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();
  }
}

My test code is as below. "mutation test" and "getter test" work. But I do not know how to test action. I cannot execute the action "add2" properly. Does anyone know how to test action?

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);
  });
});

Upvotes: 2

Views: 1177

Answers (1)

nicoramirezdev
nicoramirezdev

Reputation: 603

Try mounting a store and testing it instead of testing the module directly, like so:

const store = new Vuex.Store({
  modules: {
    counter: Counter
  }
})


it('should foo', () => {
  store.dispatch('counter/add2')

  expect(store.state.counter.count).toBe(4);
})

It is also useful to avoid sharing the state between tests to use the stateFactory flag like this:

@Module({ stateFactory: true, namespaced: true })

Upvotes: 1

Related Questions