1
votes

I need to test my Node js apllication with mocha-phantomjs.I have tried the below code to test the app but i'm getting error as 'ReferenceError: Can't find variable: require'.How to resolve this.

test.html

<html>
<head>
    <title> Tests </title>
    <link rel="stylesheet" href="./node_modules/mocha/mocha.css" />
</head>
<body>
    <div id="mocha"></div>
    <script src="../node_modules/mocha/mocha.js"></script>
    <script src="../node_modules/should/lib/should.js"></script>

    <script>
        mocha.ui('bdd');
        mocha.reporter('html');

       </script>
   <script src="test.js"></script>
    <script>
        if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
        else { mocha.run(); }
    </script>
</body>
</html>

test.js

 var module=require('../lib/requiredModule');
 var should = require('chai').should();
 describe('Testing',function(){

   it('Save Data',function(){
         module.save(content,function(err,res){
           should.not.exist(err);
         });
    });
  });

While running the html file as mocha-phantomjs test/test.html i'm getting error as

      ReferenceError: Can't find variable: require
2
The browser doesn't have require in it's API, phantomjs and mocha-phantomjs do not introduce it for you.Dominic Barnes

2 Answers

2
votes

So, I think your problem is that running your tests via the test runner basically runs them as if they were client side. Thus, it will not be able to find your native node modules (like require). You can try loading require.js in directly. Or, just use

    <script src="../node_modules/chai/chai.js"></script>
    <script>
        mocha.ui('bdd'); 
        mocha.reporter('html');
        var should = chai.should; // This will give you access to chai should.
    </script>

So you will not need to require anything that you src to. Again, think of this like you are doing everything client side.

0
votes

Take a look at browserify, which enables you to automatically include npm libraries: https://github.com/substack/node-browserify

Also recommended, are connect-browserify for auto-reloading in development https://github.com/andreypopp/connect-browserify and asset-rack https://github.com/techpines/asset-rack for automatic bundling in production.