javascriptnode.jsunit-testingbrowserifymocha-phantomjs

Require fails on a PhantomJs test


I have a simple library,

-- src/lib.js --
function libtest() {
    return 2;
}

that I want to test, which I gather will need PhantomJs. I have a test file:

-- test/lib.test.js --
var fs = require('fs');
var assert = require('assert');
describe('Test module', function() {
    var s = fs.readFileSync('../src/lib.js', 'utf8');
    eval(s);
    it('Shows name', function() {
        assert.equal(libtest(), 2);
    });
});

which I make ready for the browser:

# browserify lib.test.js -o tests.js

and then include in my main page:

-- test/index.html --
<html>
<head>
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link href="../../node_modules/mocha/mocha.css" rel="stylesheet" />
</head>
<body>
  <div id="mocha"></div>
  <script src="../../node_modules/mocha//mocha.js"></script>
  <script>mocha.setup('bdd')</script>
  <script src="tests.js"></script>
  <script>
    if (window.mochaPhantomJS) mochaPhantomJS.run();
    else mocha.run();
  </script>
</body>
</html>

however, when I run the tests:

# grunt test

I get the following error:

Running "mocha_phantomjs:all" (mocha_phantomjs) task TypeError: 'undefined' is not a function (evaluating 'fs.readFileSync('../src/lib.js', 'utf8')')

at file:///Users/ekkis/Development/tst/test/tests.js:5
at file:///Users/ekkis/Development/tst/node_modules/mocha//mocha.js:529
at file:///Users/ekkis/Development/tst/test/browser/tests.js:10 in s at file:///Users/ekkis/Development/tst/test/browser/tests.js:1 in e at file:///Users/ekkis/Development/tst/test/browser/tests.js:1 at file:///Users/ekkis/Development/tst/test/browser/tests.js:1090 Unsafe JavaScript attempt to access frame with URL about:blank from frame with URL file:///Users/ekkis/Development/tst/node_modules/mocha-phantomjs-core/mocha-phantomjs-core.js. Domains, protocols and ports must match.

which seems to be complaining about the fs being undefined. however, if the require('assert') worked, I would imagine the require('fs') should work. but I don't quite know the context in which this is run.

what am I missing?


Solution

  • ok. the answer is simply to include the library in the .html. since the tests run within the browser then the library will be available. like this:

    <body>
      <div id="mocha"></div>
      <script src="../../node_modules/mocha//mocha.js"></script>
      <script>mocha.setup('bdd')</script>
      <script src="../../src/lib.js"></script>
      <script src="tests.js"></script>