Skip to content

sagarrakshe/mocha-jsdom

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mocha-jsdom

Test frontend libraries in the console using Node.js, mocha and jsdom.

Status


Usage

$ npm i --save-dev mocha-jsdom

npm version

Use jsdom() inside your describe(...) block (or the global context). It will turn your Node.js environment into a mock browser environment supporting the full DOM and browser API. The variables window, document, history (and so on) will then be available for use.

var jsdom = require('mocha-jsdom');
var expect = require('chai').expect;

describe('mocha tests', function () {

  jsdom();

  it('has document', function () {
    var div = document.createElement('div');
    expect(div.nodeName).eql('DIV');
  });

});

How it works

mocha-jsdom is a simple glue to integrate jsdom to mocha.

Invoking jsdom() will inject before and after handlers to the current mocha suite which will setup and teardown jsdom. Here's what it does:

  • Window: global.window will be available as the jsdom.

  • Globals: global variables like document and history are propagated, and they're cleaned up after tests run.

  • Error handling: jsdom errors are sanitized so that their stack traces are shortened.

NB: Before you try this library, learn about jsdom first. In fact, you may be able to integrate jsdom into your tests without this library; this is mostly syntactic sugar and reasonable defaults.


Using with a library

Perfect for testing small DOM-consuming utilities in the console. See test/jquery.js for an example.

describe('mocha tests', function () {

  var $;
  jsdom();

  before(function () {
    $ = require('jquery');
  });

  it('works', function () {
    document.body.innerHTML = "<div>hola</div>";
    expect($("div").html()).eql("hola");
  });

});

Using with a library, alternate

You can also pass the source code via src:

describe('mocha tests', function () {
  jsdom({
    src: fs.readFileSync('jquery.js', 'utf-8')
  })

  ...
});

Configuration

You can pass jsdom options:

describe('mocha tests', function () {
  jsdom({
    parsingMode: 'xml'
  });

  ...
});

Special config

Other mocha-jsdom specific options:

  • globalize - propagates to values in window to global. defaults to true.

  • console - allows you to use console.log inside a jsdom script. defaults to true.


Thanks

mocha-jsdom © 2014+, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors (list).

ricostacruz.com  ·  GitHub @rstacruz  ·  Twitter @rstacruz

About

Simple jsdom integration with mocha

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%