Question

I'm using zombiejs + mocha to write some tests for a library that manipulates the DOM, it uses JavaScript native functions like document.createElement(), my problem is, when I run the tests I get an exception saying that 'document is not defined'.

Is it a problem with zombiejs, or with jsDOM? and how can I fix it?

here is an example of my code:

HTML:

<!DOCTYPE html>

<html>
  <head>
    <script src="mocha.js"></script>
    <script src="expect.js"></script>
    <title>XS UI Tests</title>

    <script type="text/javascript" charset="utf-8" src="../lib/mylibrary.js"></script>

    <script>
      mocha.setup('bdd');
    </script>
  </head>

  <body>
    <div id="table"></div>
    <div id="controls"></div>
    <div id="form"></div>

    <div id="mocha"></div>

    <script src="tests.js"></script>
  </body>
</html>

in tests.js:

var expect  = require( 'expect.js' )
  , Zombie  = require( 'zombie'    )
  , browser = new Zombie( { debug: true } )
;

describe( 'XS UI Tests:', function() {
  before( function( done ) {
    browser.visit( 'http://localhost:8080/test/ui.html', done );
  } );

  it( 'expect ui.html to be loaded', function() {
    expect( browser.success ).to.be( true );
  } );

  describe( 'Table Tests:', function() {
    it( 'expect div#table ( table container ) to exist', function() {
      expect( browser.query( "#table" ) ).to.be.ok();
    } );
  } );
} );

Thank you for your help

Was it helpful?

Solution

The document object is contained within the zombie browser. If your code doesn't find document, it is likely you are not running it within the zombie sandbox context.

Are you loading your library via zombie.visit('/page/with/library') or are you requiring it directly and trying to use it within the test?

It is best to test complete webpages rather than libraries. You should create a test page that has a few buttons/links on it which test different functions of the library, and pressButton or visit those with zombie.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top