Saturday, 10 December 2016

How to test a script without running it?

Let's say my app has a build script that I can run using node scripts/build.js (or just npm run build). It's a somewhat complicated script so I want to test various pieces of functionality within it independently. Luckily it's divided up into various functions that I can unit test.I have a couple of issues however:When I do require('build.js') it's going to run the script, which I don't want to do.I'm going to need to export the functions I want to test, yet I don't want anyone else reading the code (or me years later) to think that these exports comprise some kind of interface suitable for anything but testing.My solution at this point is to do something along these lines:// build.test.js process.env.TESTING = true; // could also use `NODE_ENV = test` I guess, I'm just wary of effects elsewhere const build = require('build.js'); describe('someFunction', () => { // test `build.someFunction` ... ­// build.js ... if (process.env.TESTING) { module.exports = { someFunction, ... }; } else { main(); // call the method that kicks things off } Is this an acceptable pattern? To me it doesn't feel clean to have the script know about the fact it is being tested. Also if I used ES6 exports (in the future, or now if I wanted with Babel) they'd have to be unconditional which I'm trying to avoid.Extracting the functions I want to test to their own files would solve these issues, but I really don't want to do that because they're specific to the script, there's no other benefit (at this point) in making them more generic, and I want to keep the script mostly self-contained.How would you deal with this?

Submitted December 11, 2016 at 03:33AM by NoInkling

No comments:

Post a Comment