If you’re using Node.js, you can skip this step. To run the tests, we’ll simply open the runner in a browser. The page loads Mocha, the testing libraries and our actual test files. In order to run our tests in a browser, we need to set up a simple HTML page to be our test runner page. Run the tests using the mocha command, instead of opening a browser.To include Chai, add var chai = require('chai') at the top of the test file.For Node, you don’t need the test runner file.If you want to unit test your Node.js application, follow these steps. The examples that follow are designed to work if running the tests in a browser. Testing on Node.js vs Testing in the Browser Mocha is the library that allows us to run tests, and Chai contains some helpful functions that we’ll use to verify our test results. This installs the packages mocha and chai. ![]() If you want to test Node.js code, in addition to the above, run npm install -g mocha.If you want to test code in the browser, run npm install mocha chai -save-dev.With Node installed, open up a terminal or command line in your project’s directory. If you’re unsure about how to install either npm or Node on your system, consult our tutorial: A Beginner’s Guide to npm - the Node Package Manager The easiest way to install Mocha is through npm (for which we also need to install Node.js). It’s easy to get started with, can be used for both browser-based testing and Node.js testing, and it plays nicely with other testing tools. The code for this tutorial is available from our GitHub repo.įor this article, we’ll be using Mocha. The examples and techniques shown in this article can be applied to both browser-based code and Node.js code. In this article, I’ll show you how to get started unit testing your JavaScript code. ![]() This completely eliminates any guesswork! Make a change, run your tests and if anything breaks, you’ll immediately know what happened, where the problem is and what the correct behavior should be. ![]() They will automatically detect any problems in the code for you. You could modify your code without having to worry about breaking anything, you’d have fewer bugs and you’d spend less time debugging. One thing depends on another, and then changing it breaks something else as a result.īut what if that didn’t happen? What if you had a way of knowing when something breaks as a result of some change? That would be pretty great. This is almost inevitable, especially when you have a larger amount of code. Have you ever made some changes to your code, and later found it caused something else to break? Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be! This article was peer reviewed by Panayiotis «pvgr» Velisarakos, Mark Brown and Tom Greco.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |