Reader small image

You're reading from  Vue.js 2 Cookbook

Product typeBook
Published inApr 2017
Reading LevelBeginner
PublisherPackt
ISBN-139781786468093
Edition1st Edition
Languages
Right arrow
Author (1)
Andrea Passaglia
Andrea Passaglia
author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia

Right arrow

Chapter 7. Unit Testing and End-to-End Testing

In this chapter, the following recipes will be covered:

  • Using Jasmine for testing Vue
  • Adding some Karma to your workflow
  • Testing your application state and methods
  • Testing the DOM
  • Testing DOM asynchronous updates
  • End-to-end testing with nightwatch
  • Simulating a double-click in nightwatch
  • Different styles of unit testing
  • Stubbing external API calls with Sinon.JS
  • Measuring the coverage of your code

Introduction


Testing is what really differentiates professional software from amateur software. From industry experience and studies, it has been discovered that much of the cost of software lies in correcting bugs while the software is in production. Testing software reduces bugs in production and makes correcting those bugs much less expensive.

In this chapter, you will learn how to set up your test harness and how to write unit tests and integration tests that will help speed up your app development and help it grow in complexity without leaving bugs behind.

You will gain familiarity with the most popular testing framework and slang; after completing the recipes, you will be able to confidently ship software that works just as expected.

Using Jasmine for testing Vue


Jasmine is a library for testing, it's very easy to use and it's capable of displaying the results of the tests directly in the browser. In this recipe, you will build a simple Vue application and you will test it with Jasmine.

Getting ready

I hope you don't start learning Vue with this recipe because I'm going to assume, as I will with the rest of the chapter, that you already know the basics of building simple applications in Vue.

You should also be able to find four files on the Internet. I will write the link as I found them at writing time but, of course, they may change:

You can conveniently copy-paste all the links from the https://cdnjs.com/libraries/jasmine page.

The files are dependent on each other, so...

Adding some Karma to your workflow


Karma is a JavaScript test runner. This means that it will run your tests for you. Software often grows quickly and Karma gives you a way to run all your unit tests at once. It also gives you the power to add tools that monitor for test coverage and code quality.

Karma is used traditionally in Vue projects and is present in the official Vue templates as a tool. Learning Karma is a great addition for your JavaScript toolbelt even if you are not working with Vue.

Getting ready

I would consider having completed the Using Jasmine for testing Vue recipe a prerequisite. Since Karma is a test runner, you should first be able to write a test.

We will use npm in this recipe, so you should first read the basics on how to use it in the Choosing a development environment recipe.

 

How to do it...

For this recipe, we will need the command line and npm, so be sure to have it installed before moving ahead.

In a new folder, create a file named package.json and write the following...

Testing your application state and methods


In this recipe, we will write a unit test to touch and check the state of our Vue instance directly. The advantage of testing the state of our components instead of looking for something in our web page is that we don't have to wait for the DOM to be updated and that, even if something changes in the HTML layout, the state changes much more slowly, reducing the amount of maintenance required for our tests.

Getting ready

Before trying this recipe, you should complete Adding some Karma to your workflow as we will describe how to write the test but we won't mention much about the setup of the testing environment.

How to do it...

Let's suppose that we have an application that greets you with Hello World!, but it also has a button to translate the greeting to Italian, as Ciao Mondo!. For this, you need to create a new npm project in a new folder. There, you can install the dependencies required for this recipe with the following command:

npm install --save...

Testing the DOM


In this recipe, you will learn a technique to quickly test weather the DOM or the web page itself is what it is supposed to be, even when the Vue component is not present in the page.

Getting ready

For this recipe, you should have a test setup already up and working; complete the Using Jasmine for testing Vue recipe if you don't know what that means.

I will assume that you have Jasmine installed and you can perform tests. Basically, all you need is a web page (JSFiddle is okay) and these four dependencies installed:

  • jasmine.css
  • jasmine.js
  • jasmine-html.js
  • boot.js

If you are using JSFiddle or adding them manually, remember to add them in the specified order. Find the link to these files in the Using Jasmine for testing Vue recipe.

How to do it...

Let's suppose that you are writing a component that displays the Hello World! greeting; you want to test that the greeting is actually displayed, but the web page you are testing is already complex enough and you want to test your component...

Testing DOM asynchronous updates


In Vue, when the status of your component changes, the DOM is changed accordingly; that's why we call the status reactive. The only gotcha here is that the update is not synchronous; it happens that we have to wait additional time for the changes to actually propagate.

Getting ready

For this recipe, I will assume that you have already completed the Using Jasmine for testing Vue recipe, and you know how to write a basic test.

How to do it...

The test we will write is an illustration of how Vue's update mechanism works. From there, you will then be able to write asynchronous tests on your own.

In the beforeEach function of our test suite, write the following Vue instance:

describe('my app', () => {
  let vm
  beforeEach(() => {
    vm = new Vue({
      template: `
        <div>
          <input id="name" v-model="name">
          <p>Hello from 
            <span id="output">{{name}}</span>
          </p>
        </div...

End-to-end testing with nightwatch


Sometimes unit tests just don't cut it. We may need to integrate two features developed independently and, while each works and is unit tested, there is no easy way to test them along with a unit test. Also, it defeats the purpose of unit tests--testing atomic units of the software. Integration testing and e2e (end-to-end) testing can be performed in these cases. Nightwatch is software that basically mimics a user clicking and typing around in a website. This is probably what we want as an ultimate verification that the whole system works.

Getting ready

Before beginning your journey in this somewhat advanced recipe, you should already be familiar with the command line and npm. Check the Choosing a development environment recipe if you are not familiar with them.

How to do it...

Create a new folder for this recipe and create a new file inside it, named index.html.

This file will contain our Vue application and it is what we will test. Write the following in this...

Simulating a double-click in nightwatch


This recipe is candy for all those who have struggled to simulate a double-click in nightwatch. Being one of them in the first place, I'm sympathetic. As it turns out, there is a doubleClick function in nightwatch but, at least in the opinion of the author, it doesn't work as expected.

 

Getting ready

This recipe is for developers who are starting out in nightwatch and struggle with this particular problem. You want to learn how to simulate a double-click for testing and you don't know nightwatch? Go back one recipe.

I will assume that your setup with nightwatch is working and you can launch tests. I will also assume that you have all the commands installed from the preceding recipe.

How it works...

Let's assume that you have the following Vue application in an index.html file:

<!DOCTYPE html>
<html>
<head>
  <title>7.6</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>...

Different styles of unit testing


We've discovered and used Jasmine in the previous recipes. In this recipe, we will explore and compare different styles of unit testing. This is particularly relevant because Vue templates come with Mocha and Chai preinstalled. Chai enables you to write your tests in three different styles.

Getting ready

This recipe doesn't require any particular previous knowledge, but I highly suggest that you complete the Using Jasmine for testing Vue recipe.

How to do it...

For this recipe to work, you will need two dependencies: Mocha and Chai. You will find them in no time with Google; just remember that Mocha comes in two different files: mocha.js and mocha.css. You will have to add them both if you want it to display nicely.

If you are using JSFiddle, continue as usual; otherwise, just make sure to have Vue as well in the dependencies.

Our HTML layout will look like this:

<div id="app">
  <p>{{greeting}}</p>
</div>
<div id="mocha">
</div...

Stubbing external API calls with Sinon.JS


Normally, when you do end-to-end testing and integration testing, you will have the backend server running and ready to respond to you. I think there are many situations in which this is not desirable. As a frontend developer, you take every opportunity to blame the backend guys.

Getting ready

No particular skills are required to complete this recipe, but you should install Jasmine as a dependency; this is explained in detail in the Using Jasmine for testing Vue recipe.

How to do it...

First of all, let's install some dependencies. For this recipe, we will use Jasmine to run the whole thing; you can find detailed instructions in the Using Jasmine for testing Vue recipe (the four files you'll need are jasmine.css, jasmine.js, jasmine-html.js, and boot.js, in this order)

Also, install Sinon.JS and Axios before continuing; you just need to add the js files relative to them.

We will build an application that retrieves a post at the click of a button. In the...

Measuring the coverage of your code


Code coverage is one of the most used and understandable metrics to evaluate the quality of a piece of software. If a test exercises a particular portion of code, the code is said to be covered. This suggests that that particular portion of code is working correctly and has less chance of containing bugs.

Getting ready

Before measuring your code coverage, ensure that you complete the Adding some Karma to your workflow recipe as we will be using Karma to help us.

How to do it...

Create a new directory and place a file named package.json in it. Inside it, write the following:

{
 "name": "learning-code-coverage",
 "version": "1.0.0"
}

This creates an npm project. In the same directory, run the following command to install our dependencies:

npm install vue karma karma jasmine karma-jasmine karma-coverage karma-chrome-launcher --save-dev

The package.json file changes accordingly.

The karma-coverage plugin uses the underlying software, Istanbul, to measure and display...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Vue.js 2 Cookbook
Published in: Apr 2017Publisher: PacktISBN-13: 9781786468093
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrea Passaglia

Andrea Passaglia was born in Genoa, in northern Italy. Interested about technology since his parents gave him a toy computer when he was a boy, he started studying web technologies at an early age. After obtaining his master's degree in computer engineering he worked on the design and implementation of web interfaces for companies of various sizes and in different industries (healthcare, fashion, tourism, and transport). In 2016 he moves in the silicon valley of Europe to tackle new problems in the banking industry at the Edgeverve Dublin Research and Development Labs. A backend technologist by trade, Vue.js is his first tool to bring to life his creations when it comes to the frontend. Andrea is married to a lovely Russian girl from Siberia and they often cook together mixing culinary traditions.
Read more about Andrea Passaglia