championswimmer / vuex-module-decorators

TypeScript/ES7 Decorators to create Vuex modules declaratively
https://championswimmer.in/vuex-module-decorators/
MIT License
1.8k stars 170 forks source link

How can I test if mutations was called on action? #202

Open ridermansousa-ap opened 4 years ago

ridermansousa-ap commented 4 years ago

I have an action that makes a fetch and sets the loading status...

  @MutationAction({
    mutate: ["todos", "isLoadingTodos"],
    rawError: true
  })
  async loadTodos() {
    try {
      this.commit("setIsLoadingTodos", true);

      const todos = await fetchTodos();
      return {
        todos,
        isLoadingTodos: false
      };
    } finally {
      this.commit("setIsLoadingTodos", false);
    }
  }

How can I test if setIsLoadingTodos was called twice? Or at least start with true and then is sets to false

See on CodeSandbox Edit Vuex-module-decorator tests

image

Nurpeyis commented 4 years ago

Same question. I need call 2 mutations in separate times for set isLoading.

nolleto commented 2 years ago

I had the same problem while I was fixing a module that I refactor with vuex-module-decorators.

In order to fix that I stop checking the commit and started to check the state. For example:

const promise = Todos.loadTodos();

expect(Todos.isLoadingTodos).toBeTruthy();

await promise;

expect(Todos.isLoadingTodos).toBeFalsy();

IMHO, I think this way to test it's even more reliable because what's matters for your module it's your state.

For example, if you are testing the commit (expect(commit).toBeCalledWith(...)), you are not making sure that you are setting the right state for your module because someone can make this change:

  @Mutation
  setIsLoadingTodos(isLoading) {
-   this.isLoadingTodos = isLoading;
  }

and your test will still pass ✅ .... wrongly.

But, if you test the state you expect, doesn't matter if you call 1 or more commits... or if someone renamed the mutation name. The only thing that truly matters is if your state it's correct. 😃