Dependency Mocks: A Secret Weapon for Vue Unit Tests
Join the DZone community and get the full member experience.
Join For FreeIf 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 posts by importing a Vuex ORM model Post
and calling itsall
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.
You may also like: Vue Development in 2019: What You Need to Know.
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 its rendered markup.
Home.spec.js
xxxxxxxxxx
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:
xxxxxxxxxx
"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.
xxxxxxxxxx
computed: {
posts () {
// expects VuexORM and Vuex plugins to be installed
Post.all();
}
}
Mocks to the Rescue
You might be tempted to install the 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 that the Vuex store hasn't been created and then that the model hasn't been installed into the Vuex ORM database, etc. Suddenly, you have 20 lines of code in your test and a whole lot of complexity.
But, 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.
xxxxxxxxxx
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
xxxxxxxxxx
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:
xxxxxxxxxx
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:
xxxxxxxxxx
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
xxxxxxxxxx
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 TypeError
, you'll get a green tick.
Further Reading
Published at DZone with permission of Anthony Gore, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
How To Scan and Validate Image Uploads in Java
-
Security Challenges for Microservice Applications in Multi-Cloud Environments
-
A Data-Driven Approach to Application Modernization
-
Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
Comments