How to unit test Vuex modules defined with the vuex-module-decorators syntax in Nuxt, using vue-test-utils and Jest?

Ivan Spoljaric
2 min readSep 29, 2021

If you would like to see more JS articles like this one, or if you’re interested in my services, take a look at my blogfolio: https://js-blog.dev/.

The problem

To find the answer to my question I went through the official Nuxt documentation and through the existing Stack Overflow and Github issue discussions.

But with no luck.

My AuthModule looks something like this:

The solution

After some trial and error I finally discovered the answer to my question.

The implementation looks like this:

The most important thing to realise is that the vuex-module-decorators class-based model behaves just like a vue-class-component under the hood.

All of the class-based stuff coming from vuex-module-decorators is just syntactic sugar — a wrapper around the vue-class-component API.

To quote the docs:

In your store, you use the MyModule class itself as a module…The way we use the MyModule class is different from classical object-oriented programming and similar to how vue-class-component works. We use the class itself as module, not an object constructed by the class

Another thing to keep in mind is to use createLocalVue, which enables us to use Vue classes, plugins, components etc. without polluting the global Vue class.

Adding the Vuex plugin to createLocalVue:

localVue.use(Vuex);

The AuthModule class is declared as a Vuex (namespaced) module inside the Vuex.Store constructor (as per docs).

In the implementation above, AuthModule (incl. store, actions, mutations, getters…) is re-created inside every test case with the help of the beforeEach hook (to have a clean store in every new iteration).

The rest of the code is pretty straightforward.

Check out how I tested each part of the AuthModule (actions, mutations, getters..).

That’s it. Happy unit testing :)

--

--

Ivan Spoljaric

Software Developer | Freelancer @ Toptal | Remote Worker | Lifelong Learner