

It’s always a good idea to start with a simple test that will tell us whether all the pieces of our testing suite are working properly. Now let’s write some tests! Writing a test All we have to do is put a reference to it in test.html: 1 Thankfully, there are several assertion libraries that make it easy, resulting in tests that read very much like natural English, and Mocha plays nice with all of them. It would be cumbersome to write our tests in plain JavaScript. There’s one more piece missing before we can start to write a test. Assertion libraries: The language of tests Since we aren’t actually running any tests yet, we see zero’s across the board. If we navigate to test.html we should now see some text in the top-right corner that tells us how many of our tests have passed, how many have failed, and how long the tests took to run. In a minute we’ll add another tag in line 13 that links to some actual tests.

The line inside the first tag sets Mocha up to run. (Be sure to consult the Mocha documentation to get the most up-to-date URLs to the CSS and JS files.)įinally, add a few lines of JavaScript to the HTML: 1 And in order for Mocha to display the results of our tests, we need to add a tag with the id mocha. Mocha provides a CSS file and a JS file we can link to from our test page. But for now let’s keep things simple and run it in the browser.įirst, let’s create an HTML file called test.html: 1 Mocha runs on Node.js, so it can be installed like any Node module with the Node Package Manager and run from the terminal. Before we can write any tests, though, we have to bring Mocha into our project.
UNPKG MOCHA CODE
Mocha, like other test frameworks, makes it possible for us to test our code automatically. Luckily, there are several tools available that make it easy to test most situations automatically and, at the very least, to be certain your code works the way you intend it to. To test every conceivable user behavior by hand is not only impractical, it’s impossible. What if a user clicks the wrong thing at the wrong time and it breaks? And how do you know that all the pieces of it will work properly together in every situation? You tested it on your machine for a few minutes, but something nags at you that you’re forgetting something. It’s an even better feeling to be confident that the thing you built does what it’s supposed to do. It’s a great feeling to have built something. You’ve poured your heart and soul into it. Let’s say you’ve just written the World’s Greatest App™.
