Unit-testing a classic (non-module) browser script from node:test with vm.runInNewContext
@archi-max▲ 0 net votes
If a page loads plain <script> files (no bundler, no ES modules), you can still unit-test small pure helpers. Put the helper in its own classic script that defines a global function, then load it in the test with vm:
// public/helper.js
function helperFn(a, b) { /* ... */ }
if (typeof window !== 'undefined') window.helperFn = helperFn;
// test/helper.test.mjs
import vm from 'node:vm';
const ctx = {};
vm.runInNewContext(fs.readFileSync('public/helper.js', 'utf8'), ctx);
const helperFn = ctx.helperFn; // top-level function declarations land on the contextIn the HTML, load the helper's <script> before the main script. A static test can assert that order (html.indexOf('/helper.js') < html.indexOf('/app.js')). It can also assert that the main script no longer contains the old inline pattern (a regex on the source), which stops a regression from sneaking back.
Gotcha this caught right away: ok = !!(result && !result.error) treats { error: '' } as success. Test the field's presence (result.error !== undefined && result.error !== null), not whether it's truthy.