Testing Vue with Jest

Testing Vue with Jest

In this article to show how to setup Jest in an Vue.js application. This will guide you through everything in a blank Vue.js template to test components and more

In this article to show how to setup Jest in an Vue.js application. This will guide you through everything in a blank Vue.js template to test components and more

As we’re inside of the Vue.js environment, we’ll also be using <a href="https://alligator.io/vuejs/vue-test-utils-changes/" target="_blank">vue-test-utils</a> to make it easy when interfacing with native Vue elements.

Project Setup

Setting up our testing environment is easy. In previous versions of the Vue.js CLI, we had to do this manually, but now it comes as standard with the project generation.

Ensure you have the Vue.js CLI installed on your machine by doing the following:

$ npm install -g @vue/cli
# OR
$ yarn global add @vue/cli

# Ensure you have the appropriate version (3.x.x>) with
$ vue --version

Create a new project with the CLI with the following:

$ vue create testing-vue

> Manually select features
> Babel, Linter / Preformatter, Unit Testing
> ESLint (your preference)
> Lint on save
> Jest
> In dedicated config files

$ cd testing-vue
$ code .
$ npm run serve 

Testing

Now that we’ve generated our Vue project with Jest, we can navigate to the tests/unit folder. Inside of this folder, we have a file named example.spec.js:

import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";

describe("HelloWorld.vue", () => {
  it("renders props.msg when passed", () => {
    const msg = "new message";
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    });
    expect(wrapper.text()).toMatch(msg);
  });
});

As referenced inside of our package.json, we can run this unit test by typing:

$ npm run test:unit

This gives us the results of all of the unit tests within our project. At the moment, everything passes as expected.

We can add the --watch flag to this to keep this running in the background as we create and edit new tests.

"scripts": {
  "test:unit": "vue-cli-service test:unit --watch"
}

Unit Testing

In our small example, we’ll create a new component named FancyHeading. This will represent a heading that can be customized with a title and color using props.

<template>
  <h1 :style="headingStyles">{{title}}</h1>
</template>

<script>
export default {
  data() {
    return {
      headingStyles: {
        color: this.color
      }
    };
  },
  props: ["title", "color"]
};
</script>

In order to unit test this, we’ll need to make a corresponding FancyHeading.spec.js file within the tests/unit directory.

A test suite can be thought of as a collection of tests centered around testing a particular module or functionality.

Let’s take a look at our first unit test with Jest and Vue. We’ll investigate it line by line:

import Vue from 'vue';
import FancyHeading from '@/components/FancyHeading.vue';

function mountComponentWithProps (Component, propsData) {
  const Constructor = Vue.extend(Component);
  const vm = new Constructor({
    propsData
  }).$mount();

  return vm.$el;
}

describe('FancyHeading.vue', () => {
  it('should be the correct color', () => {
    const headingData = mountComponentWithProps(FancyHeading, { color: 'red' });
    const styleData = headingData.style.getPropertyValue('color');

    console.log(styleData)

    expect(styleData).toEqual('blue');
  });

  it('should have the correct title', () => {
    const headingData = mountComponentWithProps(FancyHeading, { title: 'Hello, Vue!' });
    const titleData = headingData.textContent;

    expect(titleData).toEqual('Hello, Vue!');
  });
});

  1. We start off by importing Vue and the necessary components that we want to test.
  2. We use describe to encapsulate numerous unit tests surrounding our FancyHeading component.
  3. Each unit test is created with the it function, firstly providing a description of exactly what we’re testing, followed by a function.
  4. In our first assertion, It must have the correct color, we’re mounting our component to a new Vue instance with mountComponentWithProps.
  5. We’re then able to create a variable, styleData which contains what we expect to receive from our test.
  6. Finally, we assert that this is true by using expect. If we check our terminal with $ npm run test:unit --watch, we’ll see a PASS for this unit test.

We take a similar approach when testing the title of our heading in the second unit test.

Vue.js Testing Guide: Unit testing in Vue and Mocha

Vue.js Testing Guide: Unit testing in Vue and Mocha

Testing in Vue is really simple! In this post, you'll learn a basic unit test using Mocha and Vue.js

This document aims to outline some short examples of how to unit test using a Vue project. This guide is specifically designed to be used on the following Vue set up.

What project setup? What packages are needed?

With the above setup, you can now start writing Mocha unit tests in Vue. The steps below show how to create tests.

Creating test files

Files that are picked for the testing end with **_.spec.js_**. You can see how this is set or change this inside **_package.json_**.

package.json

"scripts": {
    "test:unit": "vue-cli-service test:unit src/**/*.spec.js"
  }
How to run tests?

In the terminal type:

npm run test:unit

Let's see how a basic unit test file will look…

import Spinner from "@/ui/Spinner";
import AppLoadingScreen from "./AppLoadingScreen";
import { shallowMount } from "@vue/test-utils";
import { expect } from "chai";

describe("AppLoadingScreen", () => {
  let component;

  beforeEach(() => {
    component = shallowMount(AppLoadingScreen);
  });

  it("should render Spinner on mount", () => {
    expect(component.find(Spinner).exists()).to.be.true;
  });
});

The numbers below reference the code AppLoadingScreen.spec.js code block above.

  1. A component spinner is imported
  2. AppLoadingScreen.vue (the Vue component we are testing is imported)
  3. **_shallowMount_**is imported from Vue utils. It creates a [**_Wrapper_**](https://vue-test-utils.vuejs.org/api/wrapper/)that contains the mounted and rendered Vue component, but with stubbed child components. A stubbed child component is a replacement for a child component rendered by the component under test. Some more details here on how stubbed components work: https://stackoverflow.com/questions/52962489/what-are-stubbed-child-components-in-vue-test-utils
  4. **_expect_** is imported from chai. expect is a chainable language to construct assertions. Assertions are used to test a specific thing in the code. Some examples of what can be chained to expect to test https://www.chaijs.com/api/bdd/

6. **_describe_**is used to outline what you are testing. This will also show in the terminal after running the test. In this case, we are testing the appLoadingScreen component.

9. **_beforeEach()_** is a Mocha method which executes the callback argument before each of the tests. We run **_shallowMount()_** inside **_beforeEach()_** so a component is mounted before every test.

10. **_shallowMount()_** method is used placing our test component inside.

13. **_it_** is where you perform individual tests. You should be able to describe the tests, in our case “it should render Spinner on mount”. This clearly outlines what the test will be.

14. **_expect_** from chai. Asserts that something should be tested. In our case we look inside our component for the Spinner component, by using **_find_** from vue utils. Find returns a wrapper of the first DOM node or Vue component matching selector. As we are using chai expect, we can chain keywords. In this case, we add **_to.be.true_**

Running the above test **_npm run test:unit_**

Displays the results of the test describe being the “AppLoadingScreen” and it being “should render Spinner on mount”.

How we would go about testing when using Vuex.

A **_.spec.js_** file that uses vuex

import Vuex from "vuex";
import { createLocalVue, shallowMount } from "@vue/test-utils";
import chai, { expect } from "chai";
import sinon from "sinon";
import sinonChai from "sinon-chai";
import Modal from "@/ui/Modal";
import BaseButton from "@/ui/BaseButton";

chai.use(sinonChai);

const localVue = createLocalVue();
localVue.use(Vuex);
localVue.component("BaseButton", BaseButton);

describe("Modal", () => {
  let store;
  const getters = {
    isModalOpen: () => true,
    activeModalName: () => "baz"
  };
  const actions = {
    TOGGLE_MODAL: () => true
  };
  let component;
  const mockMethod = sinon.spy();

  beforeEach(() => {
    store = new Vuex.Store({
      getters,
      actions
    });

    component = shallowMount(Modal, {
      store,
      localVue,
    });
  });

  describe("can close when", () => {
    it("clicking 'x'", () => {
      component.setMethods({ TOGGLE_MODAL: mockMethod });
      component.find(".modal-close-btn").trigger("click");
      expect(mockMethod).to.have.been.called.calledWith({
        isOpen: false,
        name: null
      });
    });
  });
});

The numbers below reference the code Modal.spec.js code block above.

  1. We import vuexas we are going to create a store inside the test file.
  2. createLocalVue from vue utils. Is used to create a local class of vue so we can use components, plugins and mixins without polluting the global vue class.

4. sinon is imported. sinon allows you to create test doubles. For example mock methods from the component we want to pull into the test.

5. sinon-chai is imported. Extends Chai with assertions for the Sinon.JS mocking framework.

6. The modal component is imported (the component we are testing)

7. BaseButton is imported — we have to import this component as it is registered globally.

8. chai.use is called and set to use sinonChai

11. createLocalVue is stored in a variable for reuse.

12. Set the localVueto use vuex.

13. Register the BaseButton component as it was previously registered globally.

16. Create the store variable.

17. Create the getters, matching the component getters. ( here we can change the values to help us test, for example, if something is hidden in v-if we can change to true in the test so it becomes available)

18. Create the actions, matching the component.

25. store a mockMethod using sinon.spy(). A spy call is an object representation of an individual call to a spied function, which could be a fake, spy, stub or mock method.

28. A new store is created passing the getters and actions.

33. We create the shallow mount version of the component with the localVue and store passed in.

41. setMethods allows you to use methods from the store, in this case, we are using the action we created, matching the component file action TOGGLE_MODAL. https://vue-test-utils.vuejs.org/api/wrapper-array/#setmethods

42. find is used to search for a selector in the component. From vue Utils https://vue-test-utils.vuejs.org/api/wrapper/#find

42. trigger is used to pass in the event, in this case ‘click’ is the event that would fire on this selector. https://vue-test-utils.vuejs.org/api/wrapper/trigger.html

43. Here is the test. We use expect to assert that the mockmethod to.have.been.called.calledWith chainable methods come from chai and can be used to test a variety of scenarios. calledWith can check the see what arguments have been passed in, this way we can be sure that what gets passed in does not change otherwise the test will fail and indicate why.

Summary

That’s a basic unit test using mocha and Vue.

As you can imagine each component may have different logic in with new test syntax needed. Vuex is commonly used in Vue apps, which adds another layer of complexity when testing.

With this test, we can check that a store action was called, by testing what would happen if we triggered a click event on a selector.

The store logic itself can be tested independently on its own, which would give you a detailed test of what each action and mutation are doing.

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.

What's Vue Test Utils? How to get started with Vue testing?

What's Vue Test Utils? How to get started with Vue testing?

In this tutorial we discuss vue testing, how to get started with testing and what vue test utils is. We look at creating mocks, and we look at the wrapper function.

In this tutorial we discuss vue testing, how to get started with testing and what vue test utils is. We look at creating mocks, and we look at the wrapper function.