Okay, the WK community probably isn’t the best forum for this kind of question, but the only scripts I’ve written are for Wanikani, so here goes:
I’m a novice at javascript but I’ve recently been building increasingly complex user scripts, and I’m having a great time learning.
To my observation, the biggest differences between professional and amateur code boils down to:
- Code reviews, and
- Automated testing
There are lots of tools to help with the latter, but it looks like the Jest testing framework is extremely popular and offers everything I’d want for unit/integration/e2e testing.
I used to really love the “red-light, green-light, refactor” style of test-driven development the last time I did any semi-serious programming (in ruby). I’d love to get back to it with javascript.
I’d really like to write some Jest tests for my Ganbarometer user script, but I’m kinda stumped regarding the best way to import my code into a test script.
Jest and other frameworks appear to be oriented toward React/Vue/Angular types of development frameworks with multiple source files and exported modules/components.
Since a user script is usually one monolithic file (a single IIFE in fact) with a bunch of imperative code, I’m unsure how to require
my script such that I can access my functions/classes/objects/methods/variables in my test scripts (and not execute any immediate, imperative code).
Jest expects your code to be written something like
function sum(a, b) {
return a + b;
}
module.exports = sum;
Instead of a typical imperative script like:
(function () {
"use strict";
function sum(a, b) {
return a + b;
}
console.log(sum(2, 3));
// imperatively do a bunch of other DOM manipulations, etc.
})();
Any suggestions on how to restructure my scripts such that I can require
them in my test files? I’m unclear on how to “reach into” the functions, etc. that I define in the IIFE.
I think I need to put all of my preliminary object/class/function definition stuff into a separate file that I require in the top-level user script (using Tampermonkey’s @require
directive). Is that the best practice?
Any and all suggestions/advice are more than welcome. I really have very little idea what I’m doing: please give examples if you have any specific advice!
Thanks in advance!