gotwarlost / istanbul

Yet another JS code coverage tool that computes statement, line, function and branch coverage with module loader hooks to transparently add coverage when running tests. Supports all JS coverage use cases including unit tests, server side functional tests and browser tests. Built for scale.
Other
8.7k stars 788 forks source link

Coverage not generated when mocking dependencies using vm.runInNewContext #293

Open laurentgoudet opened 9 years ago

laurentgoudet commented 9 years ago

Mocking out dependencies is essential when unit testing. Without a DI framework, a custom module loader leveraging vm.runInNewContext can be used mock some dependencies of a module as describe here by @vojtajina. However, no coverage is reported for the modules loaded using that method as there are run in a different context.

As Istanbul is as essential as mocking dependencies for me, I've added a hook for vm.runInNewContext. The only trick is that is needs to copy over the "$$cov_" global from the custom context over to its parent. Besides that it works great and my coverage has already improved :).

I haven't created a new config for it, i.e. enabling hook-run-in-context will hook both vm.runInThisContext and vm.runInNewContext.

laurentgoudet commented 9 years ago

Btw the filename then needs to be passed to vm.runInNewContext in order for Istanbul to know which file is run:

vm.runInNewContext(fs.readFileSync(filePath, 'utf8'), context, filePath);
geovanisouza92 commented 7 years ago

What's the state about this?

I'm trying to test scripts that will be run on a embedded v8 context. So, I'm using Jest using Script.runInContext with mocked globals. The tests works, but no coverage is collected.