Find the Vue.js 3 version .

Testing getters in isolation is straight forward, since they are basically just JavaScript functions. The techniques are similar to testing mutations, more info here, and actions.

The source code for the test described on this page can be found .

We will look at two getters, which operate on a store that looks like this:

  1. : gets all poodles
  2. poodlesByAge: gets all poodles, and accepts an age argument

First, let’s create the getters.

Nothing too exciting - remember that getters receive other getters as the second argument. Since we already have a poodles getter, we can use that in poodlesByAge. By returning a function in poodlesByAge that takes an argument, we can pass arguments to getters. The poodlesByAge getter can be used like this:

Let’s start with a test for .

Since a getter is just a JavaScript function that takes a state object as the first argument, the test is very simple. I’ll write my test in a getters.spec.js file, with the following code:

poodlesByAge is a bit more interesting. The second argument to a getter is other getters. We are testing , so we don’t want to involve the implementation of poodles. Instead, we can stub getters.poodles. This will give us more fine grained control over the test.

Instead of actually passing the real poodles getter, we pass in the result it would return. We already know it is working, since we wrote a test for it. This allows us to focus on testing the logic unique to poodlesByAge.

It is possible to have async getters. They can be tested using the same technique as async actions, which you can read about here.

  • When testing getters in isolation, you need to pass the state manually.
  • If a getter uses another getter, you should stub the expected return result of the first getter. This will give you more fine grained control over the test, and let you focus on testing the getter in question

The source code for the test described on this page can be found .