google-chrome-extensiongulprequirejsmocha.jsmocha-phantomjs

Testing chrome extension - require error


I have this gulp task:

gulp.task('test', function () {
    return gulp.src('test/runner.html')
        .pipe(mochaPhantomJS());
});

This is my runner.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Mocha</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
    </head>
    <body>
        <script src="../node_modules/mocha/mocha.js"></script>
        <script>mocha.setup('bdd')</script>
        <script src="../node_modules/chai/chai.js"></script>
        <script src="../node_modules/requirejs/require.js"></script>

        <script>
          var assert = chai.assert;
          var expect = chai.expect;
          var should = chai.should();
        </script>
        <script src="spec/test.js"></script>
        <script>
            if (window.mochaPhantomJS) {
              console.log('Running mochaPhantomJS...');
              mochaPhantomJS.run();
            } else {
              console.log('Running mocha...');
              mocha.run();
            }
        </script>
    </body>
</html>

And here is my test.js file:

var chrome = require('sinon-chrome');
var popup = require('../../source/scripts/popup');

describe('sumit', function(){
    before(function () {
        global.chrome = chrome;
    });
    it('Should return 1', function(){
        assert(popup.sum(0,1) === 1);
    });
})

But when I run gulp test I get this error message:

Error: Module name "sinon-chrome" has not been loaded yet for context: _. Use require([])

http://requirejs.org/docs/errors.html#notloaded

in defaultOnError at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1 in onError at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:547 in localRequire at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1433 in requirejs at file:///c:/dev/extensions/NEW_EXPRESS/node_modules/requirejs/require.js:1794


Solution

  • In the link in the error message, it implies you should use the async require method.

    So if you update test.js to the following, then it should solve that issue:

    require(['sinon-chrome'], function (chrome) { 
        var popup = require('../../source/scripts/popup');
    
        describe('sumit', function(){
            before(function () {
                global.chrome = chrome;
            });
            it('Should return 1', function(){
                assert(popup.sum(0,1) === 1);
            });
        })
    });