Reader small image

You're reading from  React.js Essentials

Product typeBook
Published inAug 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781783551620
Edition1st Edition
Languages
Right arrow
Author (1)
Artemij Fedosejev
Artemij Fedosejev
author image
Artemij Fedosejev

Artemij Fedosejev is a technical lead living in London, United Kingdom. He is a self-taught web developer who has been a web developer since the early 2000s. Artemij earned his BSc in computer science from University College Cork, Ireland. He participated in the IGNITE Graduate Business Innovation Programme, where he built and launched a website that received the Most Innovative Project award. Artemij has played a key role in creating frontend architecture using React.js and Flux for various websites. Artemij created a number of open source projects, including Snapkite Engine, Snapkite Stream Client, and other projects.
Read more about Artemij Fedosejev

Right arrow

Chapter 8. Test Your React Application with Jest

By now, you must have created a number of React components. Some of them are quite straightforward, but some are sophisticated enough. Having built both, you might have gained a certain confidence, which makes you believe that no matter how complex the user interface is you can build it with React, without any major pitfalls. This is a good confidence to have. After all that's why we're investing time in learning React. However, there is a trap that many confident React developers fall into; the act of not writing unit tests.

What is a unit test? As the name suggests, it's a test for a single unit of your application. A single unit in your application is often a function, which suggests that writing unit tests means writing tests for your functions.

Why write unit tests?


You might be wondering why you should write unit tests? Let me tell you a story from my personal experience. I had a release of a new website that I built recently. A few days later, my colleague who was using the website sent me an e-mail with a few files that the website would reject. I closely examined the files, and the requirement of having the IDs matched in both of them was met. However, the files were still rejected, and the error message said that the IDs didn't match. Can you guess what the problem was?

I wrote a function that will check whether the IDs from the two files match. The function checked both the value and the type of an ID, so even if the values were the same and the types were different, it would return no match. Turns out, that was exactly the case with the files from my colleague. The important question is how could I prevent this from happening? The answer is a number of unit tests for my function.

Creating test suits, specs, and expectations


How does one write a test for JavaScript functions? You need a testing framework, and luckily, Facebook has built its own unit test framework for JavaScript called Jest. It is built on top of Jasmine; another well-known JavaScript test framework. Those of you who are familiar with Jasmine will find Jest's approach to testing very similar. However, I'll make no assumptions about your prior experience with testing frameworks and discuss the basics first.

The fundamental idea of unit testing is that you test only one piece of functionality in your application that usually is implemented by one function. You test it in isolation, which means that all the other parts of your application that the function depends on are not used by your tests. Instead, they are imitated by your tests. To imitate a JavaScript object is to create a fake one that simulates the behavior of the real object. In unit testing, the fake object is called mock and the process of...

Installing and running Jest


First, let's install the Jest command-line interface (Jest CLI):

npm install –-save-dev jest-cli

This command installs the Jest CLI, and adds it as a development dependency to our ~/snapterest/package.json file. Next, let's edit the package.json file. We'll replace the existing "script" object:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
},

Replace the preceding object with the following one:

"scripts": {
  "test": "jest"
},

Now we're ready to run our test suit. Navigate to the ~/snapterest/ directory, and run the following command:

npm test

You should see the following message in your Terminal:

Using Jest CLI v0.4.18
 PASS  source/utils/__tests__/TweetUtils-test.js (0.065s)
1 test passed (1 total)
Run time: 0.295s

As you can see, I am using Version 0.4.18 of the Jest CLI. When you run your test, the Jest version is likely to be higher than this.

The key line in this message is as follows:

PASS  source/utils/__tests__/TweetUtils-test...

Creating multiple specs and expectations


This time, we'll create and test the collection utility module. Create the CollectionUtils.js file in the ~/snapterest/source/utils/ directory:

function getNumberOfTweetsInCollection(collection) {
  var TweetUtils = require('./TweetUtils');
  var listOfCollectionTweetIds = TweetUtils.getListOfTweetIds(collection);

  return listOfCollectionTweetIds.length;
}

function isEmptyCollection(collection) {
  return (getNumberOfTweetsInCollection(collection) === 0);
}

module.exports = {
  getNumberOfTweetsInCollection: getNumberOfTweetsInCollection,
  isEmptyCollection: isEmptyCollection
};

The CollectionUtils module has two methods: getNumberOfTweetsInCollection() and isEmptyCollection().

First, let's discuss getNumberOfTweetsInCollection():

function getNumberOfTweetsInCollection(collection) {
  var TweetUtils = require('./TweetUtils');
  var listOfCollectionTweetIds = TweetUtils.getListOfTweetIds(collection);

  return listOfCollectionTweetIds.length;
}

As...

Testing React components


Just like with utility modules, creating tests for React components starts with creating the __tests__ directory. Navigate to ~/snapterest/source/components/ and create the __tests__ directory.

The first React component that we'll test will be our Header component. Create Header-test.js in the ~/snapterest/source/components/__tests__ directory:

jest.dontMock('../Header.react');

describe('Header component', function () {

  it('renders provided header text', function () {

    var React = require('react');
    var ReactDOM = require('react-dom');
    var TestUtils = require('react-addons-test-utils');
    var Header = require('../Header.react');

    var header = TestUtils.renderIntoDocument(
      <Header text="Testing..." />
    );

    var actualHeaderText = ReactDOM.findDOMNode(header).textContent;

    expect(actualHeaderText).toBe('Testing...');

    var defaultHeader = TestUtils.renderIntoDocument(
      <Header />
    );

    var actualDefaultHeaderText...

Summary


Now you know how to create the React components and unit test them.

In this chapter, you learned the essentials of Jest; the unit testing framework from Facebook that works well with React. We discussed the test suits, specs, expectations, and matchers. We created mocks and simulated click events.

In the next chapter, we'll learn the essentials of the Flux architecture, and how to improve the maintainability of our React application.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React.js Essentials
Published in: Aug 2015Publisher: PacktISBN-13: 9781783551620
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 €14.99/month. Cancel anytime

Author (1)

author image
Artemij Fedosejev

Artemij Fedosejev is a technical lead living in London, United Kingdom. He is a self-taught web developer who has been a web developer since the early 2000s. Artemij earned his BSc in computer science from University College Cork, Ireland. He participated in the IGNITE Graduate Business Innovation Programme, where he built and launched a website that received the Most Innovative Project award. Artemij has played a key role in creating frontend architecture using React.js and Flux for various websites. Artemij created a number of open source projects, including Snapkite Engine, Snapkite Stream Client, and other projects.
Read more about Artemij Fedosejev