12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 05 : 59 : 16
Become a member
to unlock all features

    React Testing: Running tests

    Trevor MillerTrevor Miller
    0.14 - 15

    In this lesson, we walk through how to setup our tests and run them. We write a quick empty first test and assertion, so we can run the tests. Using Mocha, we can do this manually each time with the Mocha CLI. We can also automate this using task runner features from tools like Grunt, Gulp, Webpack, or npm scripts. In this course, we will use the common npm test script setup to run our tests. We will also use the Babel compiler to write our tests with modern JavaScript syntax.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    To set up my project to run my tests, I'm going to go into my package.json, and then inside of my scripts block, and I'm going to create a new test script. Inside of this script, I'm going to use the Mocha CLI that we've already installed, and then I need to tell it what test files to run.

    We're going to be placing our test files inside of source, and then in any folder, and they will have a .spec.js extension. You could use any extensions here to say that this is a test file. Some people use .test.js, or -test.js, or place these in their own test folder, but this is the convention we'll be using in this course.

    Finally, I'm using Babel as a compiler to compile my React code and my ECMAScript 2016-2015 code back into JavaScript that will in the browser today. I need to add on the compilers flag, so I'll say compilers, and then I need to tell it to run Babel core, and now we'll be able to use modern syntax in all of our test files.

    To make sure our test script is working, I've created a new file with a .spec.js extension. Let's write a basic test in there, and then we'll run it. First, I need to import our assertion library, so I'll import Expect. Next, I'll create a describe block, which Mocha gives us to describe our tests. This'll just be an empty test.

    Now for our test itself, we're going to use an it block, which Mocha gives us, and say that it should work. Finally, we'll use our Expect package to assert that true is going to equal true. To run our test, I'll jump over to my command line and type NPM test. We can see that our test is passing.