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.
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.
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.
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.
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.
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.
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.
That is how you set up Mocha and Chai for testing your library.