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 786 forks source link

mocha + babel programmatic example #670

Open mbrevda opened 8 years ago

mbrevda commented 8 years ago

I'm trying to set up a project for coverage using mocha and babel. I've looked at lots of tutorials - all the examples I have seen are cli based. Where can I find a programmatic approach to testing + generating a coverage report programmatically?

mbrevda commented 8 years ago

To answer my own question, here is what I got working. Note this uses the babel coverage plugin. If anyone knows how to avoid using this, I would prefer not to have to include more deps. Leaving open in hope that this dep can be removed!

// set up babel require hook to transparently load files
require('babel-core/register')({
    presets: ['es2015'],
    plugins: ["__coverage__"]
})

// babel wont work in this file thought
var Mocha = require('mocha'),
    glob = require('glob'),
    istanbul = require('istanbul'),
    mocha = new Mocha({}),
    collector = new istanbul.Collector(),
    reporter = new istanbul.Reporter()

// set up files to be tested by mocha
var addTests = function() {
    return new Promise(function(resolve, reject){
        glob('./**/*Test.js', (err, files) => {
            if (err) return reject(err)
            files.forEach(file => mocha.addFile(file))
            resolve()
        })
    })
}

// runner
var run = function() {
    mocha.run(failures => {

        // before exiting, print coverage report
        collector.add(global.__coverage__)
        reporter.addAll([ 'text', 'html'])
        reporter.write(collector, true, () => {
            console.log('Coverage report saved to coverage/index.html')
        })

        // exit, on non-zero if there are failed tests
        process.on('exit', () => process.exit(failures))
    })
}

// GO!
addTests().then(run)