javascript - Testing a user script with sh -


i have userscript (hopefully cross-browser compatible, though @ moment i'm running on tampermonkey) , i'm trying set test suite. or rather, trying see if approach took in creating test suite reasonable , if should/could differently.

the userscript pretty straightforward: define bunch of functions, call 1 of them work. check in <a href="https://nodejs.org/">node</a>, want define functions avoid running initial function (since there isn't browser present handle dom properties). run ugly shell script (hopefully compatible; i'm running on dash):

#!/bin/dash grep -ev '^\s*stuff\s*\(\s*\)\s*;?\s*($|//)' oeis-tools.user.js > test-cat.js ./getfunctions.sh >> test-cat.js cat test.js >> test-cat.js nodejs test-cat.js rm test-cat.js 

so drop line function invoked, cat test script, pass node. within test script have assert-like function

function shouldbe(func, args, desiredresults) {     totaltests++;     tested.push(func.name);     var actualresult = func.apply(null, args);     if (isin(actualresult, desiredresults)) return;     console.log('called ' + func.name + '(' + args.map(disp).join(', ') + ')');     if (desiredresults.length === 1) {         console.log('\texpected ' + disp(desiredresults[0]));     } else {         console.log('\texpected ' + desiredresults.map(disp).join(' or '));     }     console.log('\tgot      ' + disp(actualresult));     failedtests++; } 

which lets me call tests in form shouldbe(functiontotest, [firstinput, secondinput, etc], [correctoutput, othercorrectoutput]). (i've left out definitions of various helper functions precise definitions shouldn't matter here.)

on plus side, lets me write tests , leaves userscript untouched (no testing baggage). seems pretty hacky. there better approach?

edit: (changed answer recommendation of putting test functions in separate file)

since existence of dom precondition of stuff() function, wrap call make @ end in if statement checks existence of dom.

if (document) {     stuff(); } 

or, better yet, since function being called in 1 place,

if (document) {     /* code of stuff() */ } 

Comments