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.

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>

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();
  });
});

The test error

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

"TypeError: Cannot read property 'store' of undefined"

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();
  }
}

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.

New Vue.js Course Announced!

Looking to build fully-tested, production-ready Vue applications that are suitable for commercial purposes?

Join the pre-sale of our upcoming Enterprise Vue course!

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

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: () => []
};

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 -> ...

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)

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();
  });
});

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.


Anthony Gore

About Anthony Gore

I'm Anthony Gore and I'm here to teach you Vue.js! Through my books, online courses, and social media, my aim is to turn you into a Vue.js expert.

I'm a Vue Community Partner, curator of the weekly Vue.js Developers Newsletter, and the creator of Vue.js Developers.

If you enjoyed this article, show your support by buying me a coffee, and if you'd like to support me ongoingly, you can make a pledge through Patreon.