Setting Up Javascript Unit-Test
Learn about Webpack configuration, JavaScript dependencies, and adding modules to dev dependencies.
Webpack configuration
This is going to be a bit involved, unfortunately. Rails 5.1 or later uses the Webpacker gem, which allows us to bypass the Rails asset pipeline and use Webpack, which is an asset-bundling tool commonly used by JavaScript developers. Webpack allows us to do all the same things the old Rails asset pipeline does: module lookup, compilation, conversion to a single minified file, and so on. But Webpack is more integrated with current JavaScript tools and makes it much easier to integrate with JavaScript code that is distributed using the Node Package Manager (NPM).
That’s good news. The less-good news is that Webpack configuration can be really complicated, especially for a Rails developer who is used to convention over configuration. The Rails team has put a lot of effort into Webpacker to control the complexity of Webpack configuration, but we still sometimes need to dig into the details.
Webpack version
Author’s note: Webpacker was in version 3.2.1 when I wrote this course. It has had two or three major revisions since we started working on this course, each of which substantially changed the configuration files. It’s highly likely that there’s been another change or two between when I wrote this and when you’re reading it.
Test runner and testing tools
In this chapter, we’ll use the Karma test runner, which runs from the command line but executes the tests against browsers and plays reasonably nicely with Webpack. We’ll use Jasmine for a testing tool, mostly because of it’s easy-to-use syntax. And for good luck, we’ll throw in the TestDouble package.
JavaScript dependencies
Rails 5.1 or later uses the Yarn package manager to support its JavaScript dependencies. We need to get all these tools into the list of modules. We’ll load them with Yarn, along with some related modules:
Get hands-on with 1400+ tech skills courses.