EzDevInfo.com

blanket

blanket.js is a simple code coverage library for javascript. Designed to be easy to install and use, for both browser and nodejs. Blanket.js | Seamless javascript code coverage seamless javascript code coverage. easy to install, easy to configure, easy to use on client side and node.js. blanket.js is an open source project created by migrii team.

Blanket.js Report not showing a report with Mocha.js

I am having trouble getting the Blanket.js report to show in the browser when testing with mocha.js. My HTML file is:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Cow tests</title>
  <link rel="stylesheet" media="all" rel='nofollow' href="vendor/mocha.css">
</head>
<body>
  <div id="mocha"><p><a rel='nofollow' href=".">Index</a></p></div>
  <div id="messages"></div>
  <div id="fixtures"></div>
  <script src="vendor/mocha.js"></script>
  <script src="vendor/chai.js"></script>
  <script src="vendor/blanket.min.js" data-cover-adapter="vendor/mocha-blanket.js"></script>
  <script>mocha.setup('bdd')</script>
  <script src="cow.js" data-cover></script>
  <script src="cow_test.js"></script>
  <script>mocha.run();</script>
</body>
</html>

My cow.js file is:

// cow.js
(function (exports) {
    "use strict";

    function Cow(name) {
        this.name = name || "Anon cow";
    }
    exports.Cow = Cow;

    Cow.prototype = {
        greets: function (target) {
            if (!target)
                throw new Error("missing target");
            return this.name + " greets " + target;
        }
    };
})(this);

my cow_test.js file is:

var expect = chai.expect;

describe("Cow", function () {
    describe("constructor", function () {
        it("should have a default name", function () {
            var cow = new Cow();
            expect(cow.name).to.equal("Anon cow");
        });

        it("should set cow's name if provided", function () {
            var cow = new Cow("Kate");
            expect(cow.name).to.equal("Kate");
        });
    });

    describe("#greets", function () {
        it("should greet passed target", function () {
            var greetings = (new Cow("Kate")).greets("Baby");
            expect(greetings).to.equal("Kate greets Baby");
        });
    });
});

When i open the html file all i get is the mocha results. i have checked many times that my dependencies are in the right place and the blanket.min.js file is in the same folder as the mocha-blanket.js file which is in the same directory as mocha.js.


Source: (StackOverflow)

Grunt-Mocha-Test BlanketJS Coverage

I'm trying to setup code coverage with with grunt-mocha-test plugin for GruntJS. I have followed this guide, under the section 'Generating Coverage'.

However, running grunt produces a coverage.html report that only has coverage for the test files that were run... not my other code.

So:

  1. Does anyone know what the issue is? Ideally I do not want to use another grunt plugin.
  2. How do I filter all my /test/** files to not be included in the coverage report?

My normal mocha tests run fine via grunt, just the coverage report is the problem.

The documentation for BlanketJS doesn't really help here. Perhaps there is something in the 'options' part when requiring blanker?

Any here is my gruntfile:

mochaTest: {
            test: {
                src: watchFiles.mochaTests,
                options: {
                    reporter: 'spec',
                    require: ['server.js', 'app/tests/blanket.js']
                }
            },
            coverage: {
                src: watchFiles.mochaTests,
                options: {
                    reporter: 'html-cov',
                    // use the quiet flag to suppress the mocha console output
                    quiet: true,
                    // specify a destination file to capture the mocha
                    // output (the quiet option does not suppress this)
                    captureFile: 'coverage.html'
                }
            }
        },

And here is the blanketjs wrapper:

var path = require('path');
var srcDir = path.join(__dirname, '..');

require('blanket')({
    // Only files that match the pattern will be instrumented
    pattern: srcDir
 });
 console.log(srcDir); 

The src: watchFiles.mochaTests is just a variable above holding an array of my tests to run.


Source: (StackOverflow)

Advertisements

How can I dynamically instrument code in requirejs for blanketjs

I have a test framework where I can dynamically require files and instrument either the subject (the single file) file or all (related/required) files.

Therefore I have an array of files that I identify for require'ing and I can loop over those and set my instrument! plugin to the file path.

This is all working fine except the result from blanketjs is a string and not an object that I can work with - is there a way I can acheive this, how can I pass the string to requirejs in the onload and allow it to parse/eval it into an object like it would if I wasn't using my plugin?

Test Runner setup class

// qUnit config to add a dropdown to the header
var coverageConfig =
{
  id: 'coverage',
  label: 'Code Coverage',
  value: ['All-Files', 'Current-File'],
  tooltip: 'Enable code coverage.'
}
qUnit.config.urlConfig.push(coverageConfig); 

// settings.requireArgs is an array of urls to require for the test
if (document.location.href.indexOf(coverageConfig.value[0]) > 0)
{
  // instrument all files
  settings.requireArgs = settings.requireArgs.map(function (arg)
  {
    return 'instrument!' + arg;
  });
}
else if (document.location.href.indexOf(coverageConfig.value[1]) > 0)
{
  // instrument current file - first file is always the current file
  settings.requireArgs[0] = 'instrument!' + settings.requireArgs[0];
}

require(settings.requireArgs, function ()
{
  // settings.actionArgs are the args to the func that will be passed the    
  // required arguments
  var actionArgs = settings.actionArgs || [];
  $.merge(actionArgs, arguments);

  // fixture is a base fixture class 
  settings.action.apply(fixture, actionArgs);

  qUnit.load();
});

RequireJS plugin

define(['text'], function (text)
{
  'use strict';

  // File extension.
  var extension = '.js';
  var blanket = window.blanket;

  return {

    normalize: function (moduleName, normalize)
    {
      if (moduleName.slice(-extension.length) !== extension)
      {
        moduleName += extension;
      }
      return normalize(moduleName);
    },

    load: function (moduleName, parentRequire, onload, config)
    {
      var fullPath = parentRequire.toUrl(moduleName);

      if (config.isBuild)
      {
        onload();
      }
      else
      {
        text.load(fullPath, parentRequire, function (rawSource)
        {
          blanket.utils.cache[moduleName] = {};
          blanket.instrument({ inputFile: rawSource, inputFileName: moduleName },
            function (instrumented)
            {
              // `instrumented` is the actual instrumented code as a string
              blanket.utils.cache[moduleName].loaded = true;
              blanket.requiringFile(moduleName, true);

              // this will be an argument in settings.actionArgs in the test runner setup 
              // class - but it is a string not a JavaScript object.
              onload(instrumented);
            });
        },
        config);
      }
    }
  };
});

Source: (StackOverflow)

Mocha with Blanket, Babel and LCOV reporter

Hiho,

I've got a problem with my Mocha configuration. I've got ES6 code which should be compiled by Babel and then I want to get coverage (in LCOV format) of this ES6 code.

My approach to this problem was to use mocha, mocha-lcov-reporter, babel and blanket packages. Code structure is:

-- src
----- ...
-- test
----- spec
-------- something.spec.js
-------- ...
----- blanket.js

Where specs are in test/spec directory (matches also *.spec.js pattern) and blanket.js is:

require('blanket')({
    pattern: require('path').join(__dirname, '..', 'src')
});

Command which I prepared is:

./node_modules/.bin/mocha $(find test -name '*.spec.js') --recursive --compilers js:babel/register -r test/blanket -R mocha-lcov-reporter

So, it should run Mocha tests for all *.spec.js files, compiling them by Babel and starting test/blanket.js file before.

After starting this command I get Error: Line 1: Unexpected reserved word error from esprima.js. When I run it without requiring test/blanket file it run without problems, but ofc I haven't coverage.

Has anyone tried to do so? Do you have any ideas how to do it?


Source: (StackOverflow)

how to ensure 100% code coverage of git commits with grunt-mocha-cov

I am trying to set up a continuos integration environment (using quick build) wherein on every commit to a git branch I want to run our test suite, check code coverage and revert commits if either the test fails or the code coverage is below a certain threshold. In particular I want to ensure that the code I am checking in is 100% tested. Our test suite has been set up using grunt and mocha-hack and we are using grunt-mocha-cov for coverage. But grunt-mocha-cov instruments the whole source code. I want only the git diffs to be instrumented. Is there a way to do this?


Source: (StackOverflow)

Blanket.js code is instrumented, but will not display when running with Mocha and chai and AMD RequireJS

I've google and SO'd extensively for the answer, and have a found a number of repositories and tutorials with something that wasn't quite what I was looking for, but I attempted to adapt anyway.

According to earlier issues I've looked through, the key to Blanket.js' coverage working is that window._$blanket is defined, and mine is, along with the instrumentations of my source.

However, when my testrunner.html loads, it tends to alternate between a full fledged blanket.js report, or the actual mocha tests (with checkmarks and css and whatnot). I'm inclined to think it has to do with the source being asynchronously loaded with RequireJS.

Here's my testRunner.html:

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" rel='nofollow' href="/js/vendor/npm/mocha/mocha.css" />
    <script type="text/javascript" src="js/vendor/mocha/mocha.js"></script>
    <script type="text/javascript" src="js/vendor/require.js"></script>
    <script type="text/javascript" src="/js/test/unit/config.js"></script>
    <script type="text/javascript" src="/js/main.js"></script>
</head>
<body>
<script type="text/javascript" data-cover-only="/js/test/unit/js/some/path/to/"
        src="https://cdnjs.cloudflare.com/ajax/libs/blanket.js/1.1.4/blanket.min.js">
</script>
<script type="text/javascript" src="/js/vendor/blanket/src/adapters/mocha-blanket.js"></script>
<script>

    require(['mocha', 'chai', 'chai-jquery', 'sinon'], function(mocha, chai, chaiJquery, sinon) {

        // Init Chai
        chai.should(); //initializes chai.should()
        chai.use(chaiJquery);
        expect = chai.expect;

        mocha.setup({
            ui: 'bdd',
            ignoreLeaks: true
        });

        require([
            '../js/test/unit/js/some/path/to/AModel.test.js',
            '../js/test/unit/js/some/path/to/SModel.test.js',
        ], function(require) {
            mocha.run();
        });
    });
</script>
<div id="mocha"></div>
</body>
</html>

and here's the somemodel.test.js file:

define([
        "app",
        "moment",
        "util/utils",
    ],
    function(app) {

        describe('AModel', function() {

            beforeEach(function () {
                this.AModel = new AModel ({
                    type: undefined,
                    name: undefined, 
                });

                sinon.stub(this.AModel, 'fetch').yieldsTo('success', {
                    fun: "funk"
                });
            });

            afterEach(function () {
                this.AModel = null;
            });




            it('should get a node returned from a given ID', function() {
                var that = this;
                var nodeModel = this.AModel.getNode("node1");
                expect(nodeModel instanceof SModel).to.be.true;
            });

            it('should get the peer nodes of an object', function() {
                var temp = this.AModel.getPeerNodes("node1", "fakeType" );
                expect(temp).to.have.length(10);
            });


        });
    }
);

Source: (StackOverflow)

QUnit - testing plugin method calls, generic statements, etc

Few things to know:

  • My app heavily uses
    • jQuery
    • jQuery plugins (jQuery UI, chosen, datatable, etc)
    • Bootstrap

So I am very new to JS unit testing and maybe it will sound very very lame but I have a few questions below:

I have recently started qUnit to test my JS code and have used blanket.js to do code coverage.

Blanket JS output shows code like this as uncovered. I am wondering how/what can I do to get them covered?

    Example 1
    function resetForm(form)    {
      form.reset(); // This line shows not covered
    }

    Example 2
    $('a.staticLink').on('click', function(e)   {
      e.preventDefault();// This line shows not covered
    });

Similarly all generic bootstrap functions like show(), hide() show as not covered.

Even statements that just have a plugin call show as not-covered

       $(".chosen-select").chosen(); //not covered

Any help is greatly appreciated


Source: (StackOverflow)

Unit Test Code Coverage for a Chrome Extension

I have several QUnit tests running successfully for our extension.

I'd like to gather code coverage information, and thought I would use blanket.js to do so.

However, when I click the 'Enable coverage' button, I see several CSP violation messages in the JavaScript Console:

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' 

I've tried updating the content security policy of the extension, adding 'unsafe-inline' and 'unsafe-eval'. With the 'unsafe-inline', Chrome doesn't load the extension. And the 'unsafe-eval' option doesn't fix the problem.

Below is the snippet of CSP from my manifest.json file:

"content_security_policy": "default-src  'unsafe-inline' 'self'"

Is there a way to get blanket.js to run successfully for a Chrome extension?

If not, is there an alternative to blanket.js for Chrome extensions?

I'm currently using:

Chrome 34 blanket - v1.1.5 QUnit v1.10.0

Any help would be appreciated.


Source: (StackOverflow)

How to use Blanket.js with QUnit tests run with jQuery.noConflict(true)

I am using QUnit to test the jQuery plugin I'm writing and was hoping to use blanket to generate coverage information.

My test looks like:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>My Awesome Test Suite</title>
  <!-- Load local jQuery. This can be overridden with a ?jquery=___ param. -->
  <script src="../libs/jquery-loader.js"></script>

  <!-- Load local QUnit. -->
  <link rel="stylesheet" rel='nofollow' href="../libs/qunit/qunit.css" media="screen">
  <script src="../libs/qunit/qunit.js"></script>

  <!-- Code Coverage with Blanket -->
  <script src="../node_modules/blanket/dist/qunit/blanket.min.js"></script>

  <!-- Load local lib and tests. -->
  <script src="../build/thingToTest.js" data-cover></script>
  <script src="../build/test/thingToTest_test.js"></script>
  <!-- Removing access to jQuery and $. But it'll still be available as _$, if
       you REALLY want to mess around with jQuery in the console. REMEMBER WE
       ARE TESTING A PLUGIN HERE, THIS HELPS ENSURE BEST PRACTICES. REALLY. -->
  <script>window._$ = jQuery.noConflict(true);</script>
</head>
<body>
  <div id="qunit">
    <h1 id="qunit-header">QUnit Tests</h1>
    <h2 id="qunit-banner"></h2>
    <div id="qunit-testrunner-toolbar"></div>
    <h2 id="qunit-userAgent"></h2>
  </div>
  <ol id="qunit-tests"></ol>
  <div id="qunit-fixture">
    <div class="thingToTest-container">
    </div>
  </div>
</body>
</html>

When I open this in a browser I see the enable coverage option but when I check that option I get the error

TypeError: 'undefined' is not an object (evaluating '$.fn')
Source: file:///Users/dave/src/thingToTest/test/thingToTest.html?coverage=true:317

If I comment out the line

<script>window._$ = jQuery.noConflict(true);</script>

then blanket works just fine.

In simple cases this is acceptable, but in more complex cases I'd really want to load jQuery in noConflict mode to ensure test purity.

Is there a way to achieve this?


Source: (StackOverflow)

BlanketJS + Jasmine + RequireJS no code coverage

I am trying to get the same setup as this tutorial.

First Off. My file structure is:

/assests
/css
/font
/img
/js
    /collection
    /lib
    /model
    /plugin
    /spec
        -> Tests in here
    /view
    SpecRunner.js
    main.js
/templates
index.html
SpecRunner.html

My SpecRunner.html looks like:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Jasmine Spec Runner v2.2.0</title>

    <link rel="shortcut icon" type="image/png" rel='nofollow' href="js/lib/jasmine/jasmine_favicon.png">
    <link rel="stylesheet" rel='nofollow' href="js/lib/jasmine/jasmine.css">

    <!--
    <script type="text/javascript" src="js/lib/blanket/blanket.js"></script>
    <script type="text/javascript" src="js/lib/jasmine/jasmine.js"></script>
    <script type="text/javascript" src="js/lib/jasmine/jasmine-html.js"></script>
    <script type="text/javascript" src="js/lib/jasmine/boot.js"></script>
    <script type="text/javascript" src="js/lib/blanket/blanket_jasmine.js"></script>
    -->

    <script type="text/javascript" src="js/lib/require/require.js" data-main="js/SpecRunner.js">
    </script>   
</head>

<body>
    <!--This div is to allow the views to render. It's filled with the required garbage tags-->
    <div id="sandbox" style="overflow: hidden; height: 1px;">
        <div id="progress-bar-container">
            <div class="main_content">
            </div>
        </div>
    </div>
</body>
</html>

My SpecRunner.js looks like:

require.config({
  paths: {
    'jquery' : 'lib/jqm/jquery-1.11.2.min',
    'underscore' : 'lib/underscore/underscore',
    'backbone' : 'lib/backbone/backbone',
        //Testing Dependencies
        'blanket': 'lib/blanket/blanket',
        'jasmine': 'lib/jasmine/jasmine',
        'jasmine-html': 'lib/jasmine/jasmine-html',
        'jasmine-boot' : 'lib/jasmine/boot',
        'jasmine-blanket' : 'lib/blanket/blanket_jasmine'
  },
  shim: {
        backbone: {
          deps: ['underscore', 'jquery'],
          exports: 'Backbone'
        },
       'jasmine-boot' : {
            deps : [ 'jasmine', 'jasmine-html' ],
            exports : 'jasmine'
        },
        'jasmine-html' : {
            deps : [ 'jasmine' ]
        },
        'jasmine-blanket' : {
            deps : [ 'jasmine-boot', 'blanket' ],
            exports : 'blanket'
        },
    }
});

require(['jquery', 'jasmine-boot', 'jasmine-blanket', 'blanket'], function($, jasmine, blanket){
    blanket.options('filter', '../js/');
    blanket.options('antifilter', [ '../js/lib/', 
                                    '../js/plugin/', 
                                    '../js/spec/',
                                    '../js/SpecRunner.js',
                                    '../js/main.js'  ]);
    blanket.options('branchTracking', true); 

    var jasmineEnv = jasmine.getEnv();
    jasmineEnv.addReporter(new jasmine.BlanketReporter());
    jasmineEnv.updateInterval = 1000;

    var specs = [];
    specs.push('../js/spec/view/DetailView');

    $(document).ready(function() {
      require(specs, function(spec) {
        window.onload();
      });
    });   
});

The problem is that with this current setup I get to the point where the console just displays "waiting for blanket" and hangs.

I can get a version working by removing all the blanket and jasmine dependencies from SpecRunner.js and have them in SpecRunner.html (i.e. uncomment the script references). However this version is flawed as it does not provide any blanket code coverage.

I have tried the suggestions here with no luck.

Any advice would be appreciated.


Source: (StackOverflow)

Qunit coverage module wont load

Chrome is reporting the following error:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.

I've searched around and can't find any solution to this. I could probably go in and edit the blanketjs file to make async calls instead but not sure if that would have any impact on the way it's written. I assumed there would be updated version that address the issue but I seem to have the latest of blanket and qunit.


Source: (StackOverflow)

Blanket.js vs Istanbul-js vs JSCover

I am trying to decide on a JS test code coverage tool but cannot see clearly the differences between them. The top hits in Google are blanket.js, istanbul-js and JSCover.

Can anyone offer any information on the key differences between them and advantages/disadvantages?

Are there any other useful ones out there?


Source: (StackOverflow)

Getting accurate code coverage statistics with combined JavaScript file + Chutzpah/Blanket.js

I have a TypeScript project that uses Visual Studio's "Combine JavaScript output into file" option to create a single .js file containing all my application's code (excluding libraries). I'm using the Chutzpah Test Adapter to integrate and run Jasmine unit tests. If I run a code coverage analysis with no tests, the tool reports I have 23% test coverage:

Code coverage statistics

What is causing this inflated statistic?

My current theory is that when Chutzpah runs my code (app.js) in order to define all of the classes to be used in the tests, blanket.js (which is what Chutzpah uses under the hood to get code coverage statistics) sees that these lines are being run and counts them as a "covered line".

Is there a way to only include lines that are hit during a test (as opposed to before the test, for setup purposes) towards the final code coverage statistic? Or is this inflated number caused by something else?

Here's my chutzpah.json:

{
    "Compile": {
        "Extensions": [ ".ts" ],
        "ExtensionsWithNoOutput": [ ".d.ts" ],
        "Mode": "External"
    },
    "References": [
        { "Path": "initialize.js" },
        { "Path": "./MyApp/lib/jquery-1.11.2.min.js" },
        { "Path": "./MyApp/lib/jquery-ui.min.js" },
        { "Path": "./MyApp/lib/knockout-3.3.0.js" },

        /* other references here.... */

        { "Path": "./MyApp/app.js" }
    ],
    "Tests": [
        { "Includes": [ "**/*.ts" ], "Excludes": [ "**/*.d.ts" ] }
    ],
    "CodeCoverageIncludes": [ "*app.js*" ],
    "TestFileTimeout": 100000
}

Source: (StackOverflow)

Node.js Code Coverage of Certain Test Files

I just came into a Node.js project that has a ton of unit tests, most of which, unfortunately, are outdated and don't run. There's no test runner or any kind of code coverage tool implemented, and it is certainly not in my scope of work to refactor everything.

That being said, that doesn't stop me from wanting to check the code coverage of my work. I've looked at both Istanbul and Blanket and can't find a way to only have them run certain unit tests. Surely, there is a way so that I can get a report that, obviously, reports a very low percentage of coverage, but that I can dive into certain files and such (those that my tests hit) to ensure my code is throughly tested.


Source: (StackOverflow)

I am getting 0 % coverage 0 SLOC in mocha code coverage using blanket

I am trying to get the code coverage in MOCHA JS test. I am using the blanket and the but I am getting 0 % coverage 0 SLOC why I am not understanding. my package.json is

{
  "name": "basics",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha && mocha test --require blanket --reporter html-cov > coverage.html"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "chai": "~2.2.0",
    "mocha": "~2.2.4",
    "blanket": "~1.1.6",

  },
  "config": {
    "blanket": {
      "pattern": ["index.js"],
      "data-cover-never": "node_modules"
    }
  }
}

and index.js is

exports.sanitize = function(word){


    return word.toLowerCase().replace(/-/g, ' ');
}

exports.testToString = function(){


    return word.toLowerCase().replace(/-/g, ' ');
}

and indexSpec.js which is under test folder is

var chai = require('chai');
var expect = require('chai').expect;
var word = require('../index.js');

describe ('sanitize', function(){
    it('String matching ', function(){

        var inputWord = 'hello WORLD';
        var outputWord = word.sanitize(inputWord);
        expect(outputWord).to.equal('hello world');
        expect(outputWord).to.not.equal('HELLO WORLD');
        expect(outputWord).to.be.a('string');
        expect(outputWord).not.to.be.a('number');

    });

    it('Checke hyphen ', function(){
        var inputWord = 'hello-WORLD';
        var outputWord = word.sanitize(inputWord);
        expect(outputWord).to.equal('hello world');
    });
} )

Source: (StackOverflow)