CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-blanket

Seamless JavaScript code coverage library for both browser and Node.js environments

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

browser-utilities.mddocs/

Browser Utilities

Browser-specific functionality for script loading, CORS handling, manual file selection, and test runner integration.

Capabilities

File Loading Management

Track and manage files being loaded for coverage instrumentation.

/**
 * Track files being loaded for coverage or check/reset loading state
 * @param filename - File being loaded (undefined to reset, string to add)
 * @param done - Mark file as loaded (undefined to add, truthy to remove)
 */
function requiringFile(filename, done);

/**
 * Check if all required files have been loaded
 * @returns Whether all tracked files are loaded (outstandingRequireFiles.length === 0)
 */
function requireFilesLoaded();

Usage Examples:

// Track a file being loaded
blanket.requiringFile("src/app.js");
blanket.requiringFile("src/utils.js");

// Check loading status
console.log(blanket.requireFilesLoaded()); // false

// Mark file as loaded
blanket.requiringFile("src/app.js", true);
blanket.requiringFile("src/utils.js", true);

console.log(blanket.requireFilesLoaded()); // true

// Reset all tracked files
blanket.requiringFile();

Test Runner Integration

Setup coverage before test frameworks start execution.

/**
 * Setup coverage before test runner starts
 * @param opts - Configuration options
 * @param opts.callback - Function to call when setup is complete
 * @param opts.coverage - Enable/disable coverage (default: true)
 * @param opts.condition - Custom condition function for setup
 * @param opts.bindEvent - Event binding function
 * @param opts.checkRequirejs - Check for RequireJS (default: true)
 */
function beforeStartTestRunner(opts);

/**
 * Check if an adapter has been configured
 * @param callback - Function to call if adapter exists
 */
function hasAdapter(callback);

Usage Examples:

// Basic setup
blanket.beforeStartTestRunner({
  callback: function() {
    console.log("Coverage setup complete, starting tests");
    QUnit.start(); // or other test runner start
  }
});

// Advanced setup with conditions
blanket.beforeStartTestRunner({
  coverage: true,
  condition: function() {
    return document.readyState === 'complete';
  },
  callback: function() {
    console.log("Ready to run tests");
  }
});

// Check for adapter
blanket.hasAdapter(function() {
  console.log("Test adapter is configured");
});

Manual File Loading

Handle CORS restrictions with manual file loading dialogs.

/**
 * Display manual file loader dialog for CORS issues
 * Shows a modal dialog allowing users to manually select files for coverage
 */
function showManualLoader();

/**
 * Handle manual file loading from file picker
 * @param files - FileList from file input element
 */
function manualFileLoader(files);

Usage Examples:

// Automatically show loader on CORS errors
if (blanket.options("ignoreCors") === false) {
  // CORS error detected
  blanket.showManualLoader();
}

// Handle file selection
document.getElementById('fileInput').addEventListener('change', function(e) {
  blanket.manualFileLoader(e.target.files);
});

Reporting

Generate coverage reports in browser environment.

/**
 * Generate coverage report using configured reporter
 * @param coverage_data - Coverage statistics and file data
 */  
function report(coverage_data);

Browser-Specific Utilities

Utils Namespace

Collection of browser utility functions available as blanket.utils.

/**
 * Convert relative URL to absolute URL
 * @param url - Relative or absolute URL
 * @returns Absolute URL string
 */
utils.qualifyURL(url);

/**
 * Normalize backslashes in file paths to forward slashes
 * @param str - File path string
 * @returns Normalized path string
 */
utils.normalizeBackslashes(str);

/**
 * Match filename against pattern with browser-specific extensions
 * @param filename - File path to test
 * @param pattern - Pattern (string, array, regex, function, or special formats)
 * @returns Whether filename matches pattern
 */
utils.matchPatternAttribute(filename, pattern);

/**
 * Collect script tags from page for coverage instrumentation
 * @returns Array of selected script elements
 */
utils.collectPageScripts();

/**
 * Execute code in browser context
 * @param data - JavaScript code string to execute
 */
utils.blanketEval(data);

/**
 * Fetch file via XMLHttpRequest with error handling
 * @param url - File URL to fetch
 * @param callback - Success callback receiving file content
 * @param errback - Error callback
 * @param onXhr - Callback receiving XMLHttpRequest object
 */
utils.getFile(url, callback, errback, onXhr);

File Caching

Browser-specific file caching system.

/**
 * File cache object for storing loaded files
 */
utils.cache;

/**
 * Check if all cached files are loaded
 * @returns Whether all files in cache are loaded
 */
utils.allLoaded();

Usage Examples:

// Qualify relative URLs
const absoluteUrl = blanket.utils.qualifyURL("../src/app.js");
// Result: "http://example.com/src/app.js"

// Collect page scripts  
const scripts = blanket.utils.collectPageScripts();
scripts.forEach(script => {
  console.log("Script:", script.src);
});

// Fetch file with error handling
blanket.utils.getFile("src/app.js", 
  function(content) {
    console.log("File loaded:", content);
  },
  function(error) {
    console.error("Load failed:", error);
  }
);

CORS Handling

CORS Error Detection

Blanket.js automatically detects CORS (Cross-Origin Resource Sharing) errors when loading files via file:// protocol or cross-domain requests.

Manual Loader Dialog

When CORS errors occur, Blanket.js can display a manual file loader:

<div class='blanketDialogOverlay'>&nbsp;</div>
<div class='blanketDialogVerticalOffset'>
  <div class='blanketDialogBox'>
    <b>Error:</b> Blanket.js encountered a cross origin request error while instrumenting the source files.
    <br><br>This is likely caused by the source files being referenced locally (using the file:// protocol).
    <br><br>Would you like to try manually loading the source files?
    <input type="file" id="blanketFileLoader" multiple>
  </div>
</div>

CORS Workarounds

  1. Serve files via HTTP server (recommended)
  2. Use manual file loader for development
  3. Configure ignoreCors: true to suppress errors
  4. Use pre-instrumented files for testing

Script Collection

Automatic Script Detection

function collectPageScripts() {
  var selectedScripts = [];
  var filter = blanket.options("filter");
  
  // Collect both <script> and <blanket> tags
  var browserScripts = Array.prototype.slice.call(document.scripts);
  var blanketScripts = Array.prototype.slice.call(document.getElementsByTagName('blanket'));
  var allScripts = browserScripts.concat(blanketScripts);
  
  // Filter scripts based on pattern matching
  allScripts.forEach(function(script) {
    if (matchesFilter(script.src, filter)) {
      selectedScripts.push(script);
    }
  });
  
  return selectedScripts;
}

Script Attributes

Blanket.js recognizes several script attributes:

  • data-cover: Mark script for coverage instrumentation
  • data-cover-only: Files to include (equivalent to filter option)
  • data-cover-never: Files to exclude (equivalent to antifilter option)
  • data-cover-flags: Coverage flags (debug, branchTracking, etc.)

Example:

<script src="src/app.js" data-cover></script>
<script src="test/spec.js" data-cover-never></script>

Integration Patterns

QUnit Integration

// Wait for blanket setup before starting QUnit
blanket.beforeStartTestRunner({
  callback: function() {
    QUnit.start();
  }
});

Mocha Integration

// Mocha with blanket in browser
blanket.beforeStartTestRunner({
  callback: function() {
    mocha.run();
  }
});

Custom Integration

// Custom test framework integration
blanket.beforeStartTestRunner({
  coverage: true,
  condition: function() {
    // Custom readiness check
    return window.myTestFramework && window.myTestFramework.ready;
  },
  callback: function() {
    // Start custom test framework
    window.myTestFramework.run();
  }
});

Error Handling

File Loading Errors

  • Network errors: Handled by utils.getFile error callback
  • CORS errors: Can trigger manual loader dialog
  • Parse errors: Logged in debug mode

Manual Loader Validation

// Validate file selection
function manualFileLoader(files) {
  if (!files || files.length === 0) {
    console.error("No files selected");
    return;
  }
  
  Array.prototype.forEach.call(files, function(file) {
    if (!file.name.endsWith('.js')) {
      console.warn("Skipping non-JavaScript file:", file.name);
      return;
    }
    
    var reader = new FileReader();
    reader.onload = function(e) {
      // Process file content
      blanket.instrument({
        inputFile: e.target.result,
        inputFileName: file.name
      }, function(instrumented) {
        blanket.utils.blanketEval(instrumented);
      });
    };
    reader.readAsText(file);
  });
}

Debug Information

Enable debug mode to see browser-specific operations:

blanket.options("debug", true);

// Logs messages like:
// "BLANKET-Attempting to load file: src/app.js"
// "BLANKET-File loaded successfully: src/app.js"
// "BLANKET-CORS error detected, consider manual loading"

docs

browser-utilities.md

configuration.md

index.md

instrumentation.md

pattern-matching.md

reporting.md

test-integration.md

tile.json