Autoplay

    React Testing: Running tests

    Trevor MillerTrevor Miller

    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.

    reactReact
    0.14 - 15
    Code

    Code

    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
    Transcript

    Transcript

    00:00 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.

    00:17 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.

    00:40 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.

    01:06 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.

    01:31 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.

    Discuss

    Discuss