Mocha Test, Yeoman, Chrome Extension - google-chrome-extension

I created a project with the generator for Chrome extensions. Below is a representation of my folder structure.
my-wonderful-chrome-extension
app
scripts
common.js
test
index.html
spec
test.js
I want to test the common.js. My understanding of Mocha is that I should have a index.html file like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mocha Spec Runner</title>
<link rel="stylesheet" href="bower_components/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="bower_components/mocha/mocha.js"></script>
<script>
mocha.setup('bdd');
mocha.reporter('html');
</script>
<script src="bower_components/chai/chai.js"></script>
<script>
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should();
</script>
<!-- include source files here... -->
<script src="../app/scripts/common.js"></script>
<!-- include spec files here... -->
<script src="spec/test.js"></script>
<script>mocha.run()</script>
</body>
</html>
The test file (test.js) looks like this:
/* global describe, it */
describe('Find the root recipe node', function () {
it('Should not find an elem in null dom', function () {
console.log(dds_hmr.findRecipeRoot);
});
});
The common.js file looks like this:
var dds_hmr = {};
dds_hmr.findRecipeRoot = function (elem) {
if (elem && elem.hasAttribute("itemtype")
&& elem.getAttribute("itemtype") === "http://schema.org/Recipe") {
return [elem];
} else {
var result = [];
if (elem) {
for (var i = 0; i < elem.childNodes.length; i++) {
var child = dds_hmr.findRecipeRoot(elem.childNodes[i]);
result.concat(child);
}
}
return result;
}
};
This is the error I'm getting:
1) Find the root recipe node Should not find an elem in null dom:
ReferenceError: Can't find variable: dds_hmr
at http://localhost:9000/spec/test.js:4
at http://localhost:9000/bower_components/mocha/mocha.js:4263
at http://localhost:9000/bower_components/mocha/mocha.js:4635
at http://localhost:9000/bower_components/mocha/mocha.js:4694
at next (http://localhost:9000/bower_components/mocha/mocha.js:4561)
at http://localhost:9000/bower_components/mocha/mocha.js:4570
at next (http://localhost:9000/bower_components/mocha/mocha.js:4514)
at http://localhost:9000/bower_components/mocha/mocha.js:4538
at timeslice (http://localhost:9000/bower_components/mocha/mocha.js:5531)
What do I need to do to get the test to reference the code in the common.js file?

Turns out that the solution lies in the Grunt configuration (makes sense). In the connect key for the grunt server there is a test key. Under the property options there is another property base. Add 'app' to that list. This will include the app directory at test execution time. From there the trick is to change the script include in the index.html from
<!-- include source files here... -->
<script src="../app/scripts/common.js"></script>
to
<!-- include source files here... -->
<script src="scripts/common.js"></script>
Update: Added the Grunt section
// Grunt server and debug server setting
connect: {
options: {
port: 9000,
livereload: 35729,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
chrome: {
options: {
open: false,
base: [
'<%= config.app %>'
]
}
},
test: {
options: {
open: false,
base: [
'test',
'app',
'<%= config.app %>'
]
}
}
}

Related

Integrating Select2 with Magento 2

I'm trying to integrate Select2 with Magento2. So far I have integrated the plugin successfully but there are errors showing on the console.
What I've done:
Downloaded the select2.min.js and put it in app/design/frontend/<vendor>/<themename>/web/js/select2.min.js
Included the script in app/design/frontend/<vendor>/<themename>/Magento_Theme/layout/default_head_blocks.xml
Added this to the phtml file in script tags:
require(['jquery'],function(jquery){
jquery(document).load(function() {
jquery("#sorter2").select2();
});
});
I know I should it include it via requireJS but I can't seem to make it work.
Thanks!
You shouldn't add it in the header on every page as it's dependencies won't necessarily load. You need to add it to your themes requirejs-config here;
/app/design/frontend/<vendor>/<theme>/requirejs-config.js
In the file put this;
var config = {
paths: {
'select2': 'js/select2.min',
},
};
Now in any phtml file you can call it like this;
<script type="text/javascript">
require(['jquery','select2'],function($){
// do stuff with select
});
</script>
Something like this works:
in requirejs-config.js
var config = {
paths: {
'select2': 'SATA_SparePartsFinder/js/vendor/select2.full'
}
};
in your .phtml:
<script type="text/javascript">
require(['jquery', 'select2'], function($) {
$('#model-select').select2({language: {
noResults: function () {
return '<?= __('No results found') ?>';
}
}});
});
</script>

require.js with angular and jquery cause script error

Good day. I am beginner at require.js.
I have next scripts and css's in my html (style.css and script.js located at the same folder, where html is):
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel='stylesheet' href='style.css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.27/angular.js"></script>
<script src="https://cdn.bootcss.com/angular-ui-router/0.2.18/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.27/angular-animate.js"></script>
<script src="script.js"></script>
I am adding require.js as a first script:
<script data-main="main" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.1/require.js"></script>
and adding main.js, writing there:
requirejs.config({
baseUrl:"",
paths: {
"jquery":"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js",
"bootstrap":"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
(etc etc)
}
});
define(["jquery"], function() {
});
define(["bootstrap"], function() {
});
etc
I got
Error: Script error for "jquery", needed by: main
http://requirejs.org/docs/errors.html#scripterror
what I have to fix?
From RequireJS Documentation:
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//**never includes a ".js" extension since
//the paths config could be for a directory**.
paths: {
app: '../app'
}
});
Paths are not supposed to end with ".js". Your code should work fine by removing the ".js" from your paths.

node js chai mocha "ReferenceError: Can't find the variable require"

I am using grunt, mocha, and chai to run a basic unit test. My unit test looks like the following
describe('SPSearchConnection', function () {
describe('#performSearch()', function () {
it('should return zero or more results', function () {
var spSearchConnect = require('../index');
alert(spSearchConnect);
chai.assert.equal(-1, [1, 2, 3].indexOf(5));
});
});
});
Now when I run the test using grunt "grunt" I get the following error:
ReferenceError: Can't find variable: require
My gruntfile.js looks like this :
// Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Mocha
mocha: {
all: {
src: ['tests/testrunner.html'],
},
options: {
run: true
}
}
});
// Load grunt mocha task
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('default', ['mocha']);
};
My testrunner.html file looks like this :
<html>
<head>
<meta charset="utf-8">
<title>Mocha 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/chai/chai.js"></script>
<script>
mocha.setup('bdd')
mocha.reporter('html');
</script>
<!-- Tests -->
<script src="tests.js"></script>
<!-- Tests -->
<script></script>
<script>
// Only tests run in real browser, injected script run if options.run == true
if (navigator.userAgent.indexOf('PhantomJS') < 0) {
mocha.run();
}
</script>
</body>
</html>
Can someone tell me how to fix this please?
Your unit test has the line require('../index'), but the problem is that your test is going to run in a browser environment, which does not have a native require function (hence the ReferenceError). If you need to include a separate file you could us the "requirejs" library (which is intended for browsers). Or you could use a <script> tag in your HTML file? Or maybe just a simple Ajax call...

Require JS not working properly

I have made a simple code using require js. but output of another.js file is not coming to DOM.
this is my index.html.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Require JS app</title>
<script data-main="js/main" src="js/require.js"></script>
</head>
<body>
<div id="myapp"></div>
</body>
</html>
This is main.js file
require.config({
baseUrl: 'js/lib',
paths: {
"app": "../apps"
}
});
require(['jquery','app/another'], function($,message3) {
$('#myapp').html(message3);
})
This is another.js file
require (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
and this is anotherfile.js
define(function(){
var message2="hello world";
return(message2);
})
In another.js file replace
require (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
with
define (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
and it will work

Does Jasmine 2.0 really not work with require.js?

I'm setting up my SpecRunner.html/.js, RequireConfig.js, my paths and my shims just like I have with earlier release candidates of Jasmine + RequireJs, but now my test methods show Jasmine undefined. They've recently changed to a different method of loading Jasmine that I understand is incompatible with RequireJs.
Is my understanding correct? If so, will we ever be able to use Jasmine + RequireJs again?
The new boot.js does a bunch of the initialization and attaches it to window.onload() which has already been called by the time require.js loads Jasmine. You can manually call window.onload() to initialize the HTML Reporter and execute the environment.
SpecRunner.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<!-- specRunner.js runs all of the tests -->
<script data-main="specRunner" src="../bower_components/requirejs/require.js"></script>
</head>
<body>
</body>
</html>
specRunner.js
(function() {
'use strict';
// Configure RequireJS to shim Jasmine
require.config({
baseUrl: '..',
paths: {
'jasmine': 'tests/lib/jasmine-2.0.0/jasmine',
'jasmine-html': 'tests/lib/jasmine-2.0.0/jasmine-html',
'boot': 'tests/lib/jasmine-2.0.0/boot'
},
shim: {
'jasmine': {
exports: 'window.jasmineRequire'
},
'jasmine-html': {
deps: ['jasmine'],
exports: 'window.jasmineRequire'
},
'boot': {
deps: ['jasmine', 'jasmine-html'],
exports: 'window.jasmineRequire'
}
}
});
// Define all of your specs here. These are RequireJS modules.
var specs = [
'tests/spec/routerSpec'
];
// Load Jasmine - This will still create all of the normal Jasmine browser globals unless `boot.js` is re-written to use the
// AMD or UMD specs. `boot.js` will do a bunch of configuration and attach it's initializers to `window.onload()`. Because
// we are using RequireJS `window.onload()` has already been triggered so we have to manually call it again. This will
// initialize the HTML Reporter and execute the environment.
require(['boot'], function () {
// Load the specs
require(specs, function () {
// Initialize the HTML Reporter and execute the environment (setup by `boot.js`)
window.onload();
});
});
})();
Example spec
define(['router'], function(router) {
'use strict';
describe('router', function() {
it('should have routes defined', function() {
router.config({});
expect(router.routes).toBeTruthy();
});
});
});
Here's an alternative approach that may be simpler in some cases - use Jasmine's asynchronous support to load your AMD module before executing tests, like this:
in MySpec.js:
describe('A suite', function() {
var myModule;
// Use require.js to fetch the module
it("should load the AMD module", function(done) {
require(['myModule'], function (loadedModule) {
myModule = loadedModule;
done();
});
});
//run tests that use the myModule object
it("can access the AMD module", function() {
expect(myModule.speak()).toBe("hello");
});
});
For this to work, you'll need to include require.js in your SpecRunner.html and possibly configure require (as you normally would, e.g. by setting the baseUrl), like this:
in SpecRunner.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<script src="lib/require.min.js"></script>
<script> require.config({ baseUrl: "src" }); </script>
<script src="lib/jasmine-2.0.0/jasmine.js"></script>
<script src="lib/jasmine-2.0.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.0.0/boot.js"></script>
<script src="spec/MySpec.js"></script>
</head>
<body>
</body>
</html>
For this example, the AMD module implementation might look something like this:
in src/myModule.js:
define([], function () {
return {
speak: function () {
return "hello";
}
};
});
Here's a working Plunk that implements this complete example.
Enjoy!

Resources