Testing functionality that involves the store

Antonis Christofides
Testing nuxt applications
2 min readMay 17, 2021

I wanted to test this loggedOnUser() function:

So at first I tried this:

Unfortunately this fails with a loud bang. It isn’t even able to mount the component. The reason is that the component needs to use loggedOnUser() during mounting, and this.$store is undefined.

When Nuxt runs normally, it automatically loads machinery that causes things like this.$store to exist. This machinery isn’t loaded when we try to run the test above; you need to load it manually. Unfortunately, the documentation is silent about how to do this, and people have complained about this silence. Brandon Aaskov has actually written an article on this.

Now, purists might stop me and point out that in unit tests you are supposed to be testing the functionality of a unit (in this case the loggedOnUser() function) without any interaction with the rest of the system (in this case the store). If the unit being tested depends on another part of the system, that part (the store in this case) should be mocked. If we follow this advice, my test becomes like this:

This one passes alright. Other tests might need you to also mock $store.commit(), but if you are comfortable with mocking this is no big deal.

Are the purists right? My opinion is no. If you have function A that calls function B, you aren’t going to mock B whenever you’re testing A. The purpose of writing tests is to develop faster and cheaper, and this means avoiding mocking wherever possible. In fact, as a Django developer, I’m delighted at the fact that Django connects to the RDBMS and creates a test database at the beginning of each test run, relieving me of the duty of having to mock the RDBMS, although the RDBMS is a textbook case of a big external system that needs to be mocked. Django only takes a few seconds to create the database, and the savings are much more significant. The vuex store is not a big external system; it’s a small internal system. I don’t believe it should be mocked on every occasion.

Brandon’s solution wouldn’t work without a fight though, and since I’m a Nuxt beginner, I settled with mocking, waiting to get more experience before retrying. I’ll be writing more of these posts as I learn; think of them as a kind of personal notes that I’m writing in public.

--

--