coveraje/coveraje — Issue #24: require doesn't work for relative paths
Author: goatslacker
Created: 2012-03-10 00:11:51+00:00
State: open

Simplest use case I could make:

`hi.js`

module.exports = 'hello';

`cover.js`

var coveraje = require('coveraje').coveraje;

coveraje.cover(
"console.log('1'); var foo = require('./hi.js'); console.log('2');",
function (context, inst) {
console.log(context.module.exports);
},
{ globals: "node", colorizeShell: false }
);

1 will be printed to console. 2 will never be printed because `hi.js` will throw.

undefined: Error: Cannot find module './hi.js'

This is because `context.require` is set to the original require on
[TestRunner.js:78](https://github.com/coveraje/coveraje/blob/master/lib/TestRunner.js#L78)

This will lookup packages based on relative path, and the path is set incorrectly (it points to `node_modules/coveraje/`)

To fix this the dev would need to supply the path where the script is at. This will change the API a bit.

Suggestions:

* In `options` the dev can specify a `fileName` like so:

{ global: "node", colorizeShell: false, fileName: "/home/me/absolute_path/to/module/file.js" }

* The first parameter of `cover` should take the filename and do the file reading? This means if it's node do an fs.readFile and if it's a browser get contents via http request.

* Add another parameter to the `cover` function where the dev sets it to the filename or dirname of where the script is located.

* coveraje.setFilename('/blah/foo/bar/baz.js') ?

Afterwards it's just a matter of using node's `path` to `resolve()` the path and make it into an absolute path before passing it to require. That part is easy, I've already done that.

I can provide pull request.