Save 45% for a limited time.

Get access to all courses and lessons on egghead today.


    Setting up Unit Testing with Mocha and Chai

    Kent C. DoddsKent C. Dodds

    Every dependable library needs to have tests to ensure that you don't push accidental bugs. In this lesson, see how you can set up mocha and chai to start testing your library.



    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


    00:00 It's definitely time that we start adding some tests to this, because this library is serious and we don't want to push any breaking changes on accident. We're going to use Mocha and Chai to do our testing for this library.

    00:13 It's npm install Mocha and Chai, and we'll save these as dev dependencies, so "Save dev." Pro tip, you can actually do a shortcut here, so npmi-D is the same as npm install--save dev. Once we have those dependencies in here you'll see that they're added as dev dependencies in our packaged JSON.

    00:41 We have Chai and Mocha, they are added in our Node Modules directory. Now we can go into our source. We'll add a new file called index.test.js. In here we'll say our "Star Wars equals Require Index." We'll also say "Var expect equals Require chai.expect." Then we'll use the global describe from Mocha and we'll describe Star Wars-names.

    01:18 We'll do a simple assertion, it should work. We'll say "Expect true to be true," just as a simple assertion to make sure that our tests are running. We'll go to our package JSON now, and we'll finally be able to update our test script. Here we'll say "Mocha," and then we'll point to source index.test.js. We'll add -w, so that it watches the file system for changes.

    01:47 Now if we run npm Test, it works. That is how you set up your system to start testing with Mocha and Chai if you add them to your dev dependencies by running npm install-D Mocha Chai. Those will be added to your dev dependencies as well, and installed into your node modules.

    02:08 Then you create your test file. You require Chai, and we're going to pull off expect off of Chai. We have our node module here as well. Then we simply use the global describe from Mocha so that we can describe our test, and make our assertions with expect. Then we update our scripts, so that test is using Mocha. When we run npm test it runs our Mocha test.

    02:40 That is how you set up Mocha and Chai for testing your library.