Best practices for testing userscripts?

After much poking around, I think I at least understand enough to be dangerous.

As I’m just getting started with front-end development, I’d like to write code using modern (but proven) idioms. In particular, since all modern browsers support ECMAscript 2015 (ES6) style import and export of modules, I’d like to write any non-trivial code with multiple files, modules, and clear scoping, preferring ES6 idioms and syntax over older styles. 2015 was six coming on seven years ago! It seems silly not to at least start with ECMAscript 2015 conventions.

But as I’ve explained, I’d also like to use a test-driven development process (TDD).

The most popular Javascript testing framework, Jest, apparently still requires “commonjs” style modules, however, so I’ll configure it to use Babel to automate the conversion when running my tests.

To simplify deployment, I’ll also use webpack to bundle all of my module files into a smaller number of files that I can @require in my Tampermonkey scripts. (Rather than @requireing every individual module directly. The user script itself then becomes simple, imperative code, calling objects and methods from the bundle (where all the heavy lifting occurs).

Specific to my GanbarOmeter script, I’m planning to re-write it to import two modules that might be useful in other contexts:

  • DashboardWidgets to render and display gauges and bar graphs.
  • ReviewMetrics to retrieve, parse, calculate, and cache various things using WKOF and the Wanikani APIv2.

If I do it right, the overall user script should become much shorter, easier to understand, and more maintainable, and the code in the modules should be well-tested and easy to use in other contexts.

I write all this in the hope that someone will stop me if I’m about to make a huge mistake or have misunderstood anything important!

3 Likes