Using jsdom and mocha for testing

The JavaScript space for testing code, and specifically browser-based code, has been changing quite a bit recently.  There are more options now than when I recently was working on a project, but I found a pretty simple way to test some jQuery functionality while in Mocha.

First, the code:

Second, the caveats:

  • As you can see in the code comments, the module is using a module and not referencing it. This isn’t ideal. We’re adding jQuery via the global namespace. I haven’t found a way to reference jQuery in the module if it’s not defined yet, but that would get around this sticking point.
  • Using jsdom to run the tests like this, you need to build/populate the DOM objects you want. For my use case, it works out OK, but may not work for bigger testing demands.
  • As mentioned, there are plenty of other options for testing full browser pages and testing within different browsers. Be sure to use the things you need for your project!