DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

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

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
  1. DZone
  2. Culture and Methodologies
  3. Methodologies
  4. Dependency Mocks: A Secret Weapon for Vue Unit Tests

Dependency Mocks: A Secret Weapon for Vue Unit Tests

Anthony Gore user avatar by
Anthony Gore
CORE ·
Updated Jan. 08, 20 · Tutorial
Like (4)
Save
Tweet
Share
24.60K Views

Join the DZone community and get the full member experience.

Join For Free

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

HTML




x
15


 
1
<template>
2
  <ul>
3
    <li v-for="post in posts">{{ post.title }}</li>
4
  </ul>
5
</template>
6
<script>
7
import Post from "@/store/models/Post"
8
export default {
9
  computed: {
10
    posts () {
11
      Post.all();
12
    }
13
  }
14
}
15
</script>
8
export default {



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

JavaScript




xxxxxxxxxx
1


 
1
import { shallowMount } from "@vue/test-utils";
2
import Home from "@/views/Home";
3
 
          
4
describe("Home.vue", () => {
5
  it("should render correctly", () => {
6
    wrapper = shallowMount(Home);
7
    expect(wrapper).toMatchSnapshot();
8
  });
9
});



The Test Error

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

Plain Text




xxxxxxxxxx
1


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

JavaScript




xxxxxxxxxx
1


 
1
computed: {
2
  posts () {
3
    // expects VuexORM and Vuex plugins to be installed
4
    Post.all();
5
  }
6
}



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.

Shell




xxxxxxxxxx
1


 
1
mkdir src/store/models/__mocks__
2
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

JavaScript




xxxxxxxxxx
1


 
1
module.exports = {
2
  all: () => []
3
};


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:

Plain Text




xxxxxxxxxx
1


 
1
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:

Plain Text




xxxxxxxxxx
1


 
1
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

JavaScript




xxxxxxxxxx
1
10


 
1
import { shallowMount } from "@vue/test-utils";
2
import MyComponent from "@/MyComponent";
3
jest.mock("@/store/models/Post");
4
 
          
5
describe("MyComponent.vue", () => {
6
  it("should render correctly", () => {
7
    wrapper = shallowMount(MyComponent);
8
    expect(wrapper).toMatchSnapshot();
9
  });
10
});



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

  • Visually Test Vue.js Applications Using Storybook.
  • Knowing What To Test — Vue Component Unit Testing.
  • Why Do We Unit Test? And What’s the Purpose of Code Coverage?
unit test Dependency graph

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

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: