Unit testing JavaScript that runs in your browser
Recently I had the privilege of setting up a unit testing suite for a front-end application I work on. I thought that the setup might be useful for other folks looking to do the same thing so I decided to write up a blog post detailing the setup. I’m writing tests in this post for the ExtJS enterprise web framework by Sencha, and there are a few prerequisites that you need before you can start writing tests. You’ll need:
- NPM or Yarn (I prefer yarn)
- Sencha Cmd
- The ExtJS framework
ExtJS is an enterprise framework, but there is a free and open source version that you can download here. You do need to provide your email and it’s more for evaluation or training purposes than it is for use in any real projects. I picked it because ExtJS uses a Java based bundler built into Sencha Cmd to bundle and minify JavaScript. Because most other implementations of mocha and chai use node, node modules, and webpack I thought it would be useful to write a guide for ExtJS to show how testing can be done if you need a browser. Before we get started with unit testing, though, you’ll need to follow this guide on Sencha’s website. Once you’re done you should be able to run sencha app watch in your project directory and navigate to localhost:1841 to get the page below.
Great! Now we can initialize the NPM/Yarn package.json for our dependencies. Run npm or yarn init but pass it the -y flag to ignore any questions. We won’t actually be using Yarn or NPM to package our application, but we will use them to run tests. Once your package has been initialized, install the mocha, mocha-chrome, and chai packages. If it’s not clear already, you will also need chrome to run mocha-chrome tests. Once the packages are installed we can start writing and running tests.
Create an html file and a Javascript file to contain your tests. Copy the example HTML file from the mocha-chrome git repository and paste it into your test html file. Once you’ve done that import the UUT and test file to the html file in a script tag. Then pass the test file to mocha-chrome like so:
This will open up headless chrome and execute the tests inside chrome. This strategy works great for quickly unit testing projects that aren’t node based and need DOM APIs. If you’d like to see the project in action you can clone it here!