Skip to content

Instantly share code, notes, and snippets.

@searls
Last active December 25, 2015 15:49
Show Gist options
  • Save searls/7001427 to your computer and use it in GitHub Desktop.
Save searls/7001427 to your computer and use it in GitHub Desktop.
get istanbul and sandboxed-module to party
SandboxedModule = require('sandboxed-module')
global.requireSubject = (path, requires) ->
SandboxedModule.require("./../../#{path}", {requires})
_ = require('underscore')
coverageVariable = _(global).chain().keys().find((k) -> k.indexOf("$$cov_") == 0).value()
if coverageVariable?
fs = require("fs")
SandboxedModule::_getCompileInfo = ->
localVariables = []
localValues = []
for localVariable of @locals
localVariables.push localVariable
localValues.push @locals[localVariable]
sourceToWrap = instrument(fs.readFileSync(@filename, "utf8"), @filename)
if @filename.search(".coffee$") != -1
try
coffeeScript = require("coffee-script")
sourceToWrap = coffeeScript.compile(sourceToWrap)
source = "global = GLOBAL = root = (function() { return this; })();" + "(function(" + localVariables.join(", ") + ") { " + sourceToWrap + "\n" + "return global;\n" + "});"
source: source
parameters: localValues
snagInstrumentTransformerFromIstanbul = ->
Instrumenter = require('istanbul').Instrumenter
instrumenter = new Instrumenter({coverageVariable})
instrumenter.instrumentSync.bind(instrumenter)
instrument = snagInstrumentTransformerFromIstanbul()
@searls
Copy link
Author

searls commented Oct 16, 2013

Turns out this actually works. Basically we monkey-patch sandboxed-module such that what it wraps is actually instrumented JavaScript. (We get that instrumented JavaScript by figuring out what the global coverage variable is in order to generate an istanbul instrumentation transformer function)

In this case, this is just stuck in a spec helper in my test suite. The global.requireSubject() is just a little convenience we use for requiring the thing under test, it's not entirely pertinent.

@gotwarlost
Copy link

cool.

@calvinmetcalf
Copy link

I had a similar issue when I tried to get something I build with component to build with browserify, I ended up making a grunt plugin that would use espirma to rename all the instances of require in one of them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment