DEV Community

Cover image for Dependency Mocks - A Secret Weapon for Vue Unit Tests
Anthony Gore
Anthony Gore

Posted on • Updated on

Dependency Mocks - A Secret Weapon for Vue Unit Tests

If your Vue single-file components have dependencies, you'll need to handle the dependencies somehow when you unit test the component.

One approach is to install the dependencies in the test environment, but this may overcomplicate your tests.

In this article, I'll show you how to mock a module file in Jest by replacing it in your component's graph of dependencies.

Note: this article was originally posted here on the Vue.js Developers blog on 2019/09/16.

Example scenario

Say we have a single-file component that we want to test called Home.vue. This component is part of a blog app and its main job is to display post titles.

To do this, it retrieves the posts by importing a Vuex ORM model Post and calling the all method. It doesn't matter if you're unfamiliar with Vuex ORM, the important point is that the Post model is a dependency of this component.

Home.vue

<template>
  <ul>
    <li v-for="post in posts">{{ post.title }}</li>
  </ul>
</template>
<script>
import Post from "@/store/models/Post"
export default {
  computed: {
    posts () {
      Post.all();
    }
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

The unit test

Now we want to write a unit test for this component to confirm that it renders correctly.

The details of this test aren't important, but here's how we might write it: first, we'd mount the component using Vue Test Utils. Second, we'd check the mounted component against a snapshot of it's rendered markup.

Home.spec.js

import { shallowMount } from "@vue/test-utils";
import Home from "@/views/Home";

describe("Home.vue", () => {
  it("should render correctly", () => {
    wrapper = shallowMount(Home);
    expect(wrapper).toMatchSnapshot();
  });
});
Enter fullscreen mode Exit fullscreen mode

The test error

If we try to run this test, we'll get an error:

"TypeError: Cannot read property 'store' of undefined"
Enter fullscreen mode Exit fullscreen mode

The reason for this error is that the Post Vuex ORM model in the component depends on both Vuex ORM and Vuex, and neither plugin is present in the test Vue instance.

computed: {
  posts () {
    // expects VuexORM and Vuex plugins to be installed
    Post.all();
  }
}
Enter fullscreen mode Exit fullscreen mode

Mocks to the rescue

You might be tempted to now install VuexORM and Vuex on the test Vue instance. The problem with this approach is that the errors won't stop there; next, it will complain the Vuex store hasn't been created, then that the model hasn't been installed into the Vuex ORM database etc etc. Suddenly, you have 20 lines of code in your test and a whole lot of complexity.

But the here's the thing: it's not important for this unit test that the posts come from the Vuex store. All we need to do here is satisfy the dependency, so that's why we'll turn to mocking.

Creating a mock

The easiest way to create a mock is to first create a directory mocks adjacent to the file you want to mock, then create the mock module in that new directory. If you follow this recipe, Jest will automatically pick the file up.

$ mkdir src/store/models/__mocks__
$ touch src/store/models/__mocks__/Post.js
Enter fullscreen mode Exit fullscreen mode

Inside the new file, export a Common JS module. For the mock to work, you'll need to stub any method of the Post model that the component calls.

The only method used in Home is all. This method will retrieve all the items in the store. The output of this method is then used to feed the v-for. So all we need to do is make all a function that returns an array, and the Home component will be happy.

src/store/models/__mocks__/Post.js

module.exports = {
  all: () => []
};
Enter fullscreen mode Exit fullscreen mode

How Jest resolves dependencies

We now want to make it so the Home component uses the mock Post model instead of the "real" Post model.

Before I show you how to do that, I need to briefly explain how Jest, like Webpack, builds a graph of dependencies when it runs your test code. In other words, it starts with your test file, then follows each import and require statement, noting every module needed.

Currently, one path of that dependency graph relevant to what we're discussing would be this:

Home.spec -> Home -> Post -> Vuex ORM -> Vuex -> ...
Enter fullscreen mode Exit fullscreen mode

It's this path of dependencies that's the source of the error we're experiencing.

Fortunately, Jest allows us to replace modules in the dependency graph with ones we specify. If we use our Post mock, the above path would be modified to look like this:

Home.spec -> Home -> Post (mock)
Enter fullscreen mode Exit fullscreen mode

The crux of the solution is that, unlike the real Post model, the mock has no further dependencies, and so the TypeError should no longer occur if we use it.

Using the mock

To use the mock, we use the jest.mock method. This goes at the top of the file, as it's handled at the same time as import and require statements.

The first argument is the module you want to mock, in this case, "@/store/models/Post". If you put the mock in a __mocks__ directory as described above, that is all that is required for this to work.

Home.spec.js

import { shallowMount } from "@vue/test-utils";
import MyComponent from "@/MyComponent";
jest.mock("@/store/models/Post");

describe("MyComponent.vue", () => {
  it("should render correctly", () => {
    wrapper = shallowMount(MyComponent);
    expect(wrapper).toMatchSnapshot();
  });
});
Enter fullscreen mode Exit fullscreen mode

When you run this test again, Jest will ensure the dependency graph is modified to replace "@/store/models/Post" with the mock you created and instead of the Type Error you'll get a green tick.


Enjoy this article?

Get more articles like this in your inbox weekly with the Vue.js Developers Newsletter.

Click here to join!


Top comments (0)