Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nyc builtin source transformer #63

Open
skeggse opened this issue Jul 26, 2017 · 4 comments
Open

nyc builtin source transformer #63

skeggse opened this issue Jul 26, 2017 · 4 comments

Comments

@skeggse
Copy link

skeggse commented Jul 26, 2017

Related to #25.

It'd be nice if the istanbul transformer also supported nyc, which in turn supports subprocesses. I got this working with the following voodoo, but I wasn't sure whether this was the supported mechanism per https://github.com/istanbuljs/nyc. Thoughts? Is this in scope?

function maybeCoverage() {
  return Object.keys(require.cache).some((path) => /node_modules\/nyc/.test(path));
}

SandboxedModule.require('.../index.js', {
  // Voodoo magic to support nyc.
  sourceTransformers: maybeCoverage() ? {
    nyc(source) {
      const Instrumenter = require('nyc/lib/instrumenters/istanbul'),
        instrumenter = Instrumenter(process.cwd(), {}),
        instrumentMethod = instrumenter.instrumentSync.bind(instrumenter);
      return instrumentMethod(source, this.filename);
    }
  } : {}
});
@NathanGRomano
Copy link

Where should I put this snippet?

@skeggse
Copy link
Author

skeggse commented Feb 2, 2018

In a test fixture or mock where you have access to SandboxedModule.

@mariecl
Copy link

mariecl commented Feb 7, 2018

The way I use the above snippet is the following:

nycTransformer.js (placed at the root of my test folder)

'use strict';

function maybeCoverage() {
  return Object.keys(require.cache).some((path) => (/node_modules\/nyc/).test(path));
}

module.exports = maybeCoverage() ? {
  nyc(source) {
    const Instrumenter = require('nyc/lib/instrumenters/istanbul');
    const instrumenter = Instrumenter(process.cwd(), {});
    const instrumentMethod = instrumenter.instrumentSync.bind(instrumenter);
    return instrumentMethod(source, this.filename);
  },
} : {};

Then in test.js

'use strict';

const assert = require('assert');
const nycTransformer = require('../nycTransformer');
const sandbox = require('sandboxed-module');

it('should do something', function onTest() {
  const sandboxedFile = sandbox.require('path', {
     singleOnly: true,
     requires: { /* */},
     sourceTransformers: nycTransformer,
  });
  assert('something');
});

I hope that helps!

@NathanGRomano
Copy link

NathanGRomano commented Feb 21, 2018 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants