I have some tests running with RequireJS and Jasmine. I have a Jasmine test harness file that looks like this:
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="./Scripts/jasmine/jasmine.css" />
<script type="text/javascript" src="./Scripts/jasmine/jasmine.js"></script>
<script type="text/javascript" src="./Scripts/jasmine/jasmine-html.js"></script>
<script type="text/javascript" src="./Scripts/jasmine/boot.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
<script type="text/javascript">
require(["fakeTest"], function () {
window.onload();
});
</script>
</head>
<body>
</body>
</html>
My fakeTest file is very simple:
define(["require", "exports"], function (require, exports) {
describe("fake test", function () {
it("test nothing", function () {
expect(1).toEqual(1);
});
});
});
If I run this in FireFox/Chrome then everything works fine; I see one test and that it passed. If I run this with PhantomJS though, I start getting problems. Running it with the remote debugger flag I get the error:
Error: Cannot find module 'fakeTest'
phantomjs://bootstrap.js:299 in require
phantomjs://bootstrap.js:263 in require
If I try changing my harness file so that it says requirejs[("fakeTest"...... instead of just require, I get this error:
Error: Script error for "fakeTest"
http://requirejs.org/docs/errors.html#scripterror
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:140
in defaultOnError
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:544
in onError
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1732
in onScriptError :0 in appendChild
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1952
in load
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1679
in load
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:829
in load
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:819
in fetch
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:851
in check
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1177
in enable
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1550
in enable
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1162
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:131
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:56
in each
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1114
in enable
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:783
in init
https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js:1453
If I put in a completely invalid module name, I get the same errors in both cases.
I'm totally lost as to why this is happening. I've played around with changing the path for fakeTest in the harness file but nothing changes. I've simplified the harness file as much as I could, but since I'm still seeing this i'm not sure what else to try. Anyone have any ideas?
edit
I've removed everything to do with Jasmine and just have fakeTest do an alert. Now I get errors saying
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script>
<script type="text/javascript">
require(["fakeTest"], function () {});
</script>
</head>
<body>
</body>
</html>
and
define(["require", "exports"], function (require, exports) {
alert('foo');
});
"ReferenceError: Can't find variable: requirejs"
Instead of write html use karma with requirejs plugin.
karma.conf.js
module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'Scripts/**/*.js', included: false},
{pattern: 'test/*.js', included: false},
'test/test-main.js'
],
// list of files to exclude
exclude: [],
browsers: ['PhantomJS']
});
};
test/test-main.js
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
// example of using a couple path translations (paths), to allow us to refer to different library dependencies, without using relative paths
paths: {
// Put Your requirejs config here
},
// example of using a shim, to load non AMD libraries (such as underscore)
shim: {
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
This is example files. Fix it and run
karma run
Instead of
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
use
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"
data-main="Tests/main"></script>
Move test files to Tests directory.
In Tests/main.js use Your requirejs config and run main tests file.
var deps = ['Tests/fakeTest'];
require.config({
baseUrl: '..',
paths: {
'jasmine': ['Scripts/jasmine//jasmine'],
'jasmine-html': ['Scripts/jasmine/jasmine-html'],
'jasmine-boot': ['Scripts/jasmine/boot']
},
// shim: makes external libraries compatible with requirejs (AMD)
shim: {
'jasmine-html': {
deps : ['jasmine']
},
'jasmine-boot': {
deps : ['jasmine', 'jasmine-html']
}
}
});
require(['jasmine-boot'], function () {
require(deps, function(){
//trigger Jasmine
window.onload();
})
});
In index.html run only Tests/main.js file:
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="./Scripts/jasmine/jasmine.css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js" data-main="Tests/main"></script>
</head>
<body>
</body>
</html>
Related
Can I load mocha module asynchronously in browser? I can do it for sure with chai. Is there any workaround to make mocha work in amd-like style ?
require.config({
baseUrl: "/scripts",
paths: {
"mocha": "framework/mocha",
"chai": "framework/chai",
"first": "custom/first"
}
});
require(['first', 'mocha', 'chai'], function (first, mocha, chai) {
first.echo();
console.log('something');
console.log('something');
mocha.ui('tdd');
var assert = chai.assert;
suite('"Home" Page Tests', function () {
test('page should contain link to contact page', function () {
assert($('a[href="/contact"]').length);
});
});
mocha.run();
console.log('whatever');
});
in the code sample above first and chai work fine, while mocha is undefined.
Mocha is not AMD-aware so if you are going to load Mocha using RequireJS, you need a shim for it. Here is an index.html file that contains a minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
<link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" />
<script type="text/javascript" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<div id="mocha"></div>
<script>
require.config({
paths: {
mocha: 'node_modules/mocha/mocha',
},
shim: {
mocha: {
exports: "mocha",
}
},
});
require(["mocha"], function (mocha) {
mocha.setup("bdd");
it("foo", function () {});
mocha.run();
});
</script>
</body>
</html>
You need to have run npm install requirejs mocha in the same directory where index.html is located.
In cases where I want to be able to use the Mocha constructor I use this shim instead:
shim: {
mocha: {
exports: "mocha",
init: function () { return {mocha: mocha, Mocha: Mocha }; }
}
},
Can I load mocha module asynchronously in browser? I can do it for sure with chai. Is there any workaround to make mocha work in amd-like style ?
require.config({
baseUrl: "/scripts",
paths: {
"mocha": "framework/mocha",
"chai": "framework/chai",
"first": "custom/first"
}
});
require(['first', 'mocha', 'chai'], function (first, mocha, chai) {
first.echo();
console.log('something');
console.log('something');
mocha.ui('tdd');
var assert = chai.assert;
suite('"Home" Page Tests', function () {
test('page should contain link to contact page', function () {
assert($('a[href="/contact"]').length);
});
});
mocha.run();
console.log('whatever');
});
in the code sample above first and chai work fine, while mocha is undefined.
Mocha is not AMD-aware so if you are going to load Mocha using RequireJS, you need a shim for it. Here is an index.html file that contains a minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
<link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" />
<script type="text/javascript" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<div id="mocha"></div>
<script>
require.config({
paths: {
mocha: 'node_modules/mocha/mocha',
},
shim: {
mocha: {
exports: "mocha",
}
},
});
require(["mocha"], function (mocha) {
mocha.setup("bdd");
it("foo", function () {});
mocha.run();
});
</script>
</body>
</html>
You need to have run npm install requirejs mocha in the same directory where index.html is located.
In cases where I want to be able to use the Mocha constructor I use this shim instead:
shim: {
mocha: {
exports: "mocha",
init: function () { return {mocha: mocha, Mocha: Mocha }; }
}
},
I'm getting the exact error as found here: (window.beforeEach || window.setup) is not a function. However the fix did not work, the author of the tutorial series here even mentioned the same fix.
Here is the Tuts+ author's fix:
Which is simply to place the angular-mock script tag after the Mochai and Chai scripts. Which I did so below:
test/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mocha Spec Runner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="../app/favicon.ico">
<link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
<link href="bower_components/mocha/mocha.css" rel="stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/mocha/mocha.js"></script>
<script src="../bower_components/chai/chai.js"></script>
<!-- see Angular-mocks is here :( -->
<script src="../bower_components/angular-mocks/angular-mocks.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="main.spec.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
My main.spec.js file
/**
* #name Mocha Test Runner
* #desc Describes and runs our dashboard tests
*/
var assert = chai.assert;
var expect = chai.expect;
// This Test is designed to fail on purpose
describe('User Login', function() {
console.log('User Login');
describe('Login Failed', function() {
console.log('Login Failed');
if ('Incorrect login should fail', function() {
module('loginController')
inject(function($injector) {
apiFactory = $injector.get('ApiFactory');
});
expect(apiFactory).to.be.an('number');
});
});
});
My Gulp tasks
gulp.task('serve', function() {
return browserSync.init({
notify : false,
port : 3333,
server: {
baseDir: ['app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
gulp.task('serve-test', function() {
browserSync.init({
notify : false,
port : 4444,
server: {
baseDir: ['test', 'app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
In your index.html file, you include the angular-mocks.js script before the call to mocha.setup('bdd'). angular-mocks.js is implemented as an immediately-invoked function expression which attempts to use window.beforeEach. (https://github.com/angular/bower-angular-mocks/blob/master/angular-mocks.js#L2586)
However, mocha.js is not immediately invoked and has to be initialized with the mocha.setup function in order to add its magic to the runtime environment.
Try reversing the order of these script tags, so that mocha.js is included and initialized before angular-mocks.js.
<script src='bower_components/mocha/mocha.js'></script>
<script src='bower_components/chai/chai.js'></script>
<script>
mocha.setup('bdd');
</script>
<script src="bower_components/angular-mocks/angular-mocks.js"></script>
I am trying to setup a QUnit environment using requirejs and grunt-contrib-qunit.
Here is what I have.
gruntfile:
qunit: {
all: {
options: {
urls: [
'http://localhost:8000/qunit/qunit-test-suite.html'
]
}
}
},
connect: {
server: {
options: {
port: 8000,
base: '.'
}
}
},
qunit-test-suite.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>QUnit Tests Suite: travis CI Test</title>
<link rel="stylesheet" href="../components/libs/qunit/qunit/qunit.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="../components/libs/qunit/qunit/qunit.js"></script>
<script>
QUnit.config.autoload = false;
QUnit.config.autostart = false;
</script>
<script data-main="qunit" src="../components/libs/requirejs/require.js"></script>
</body>
</html>
qunit.js:
require.config({
baseUrl: "../",
paths: {
'jquery': 'components/libs/jquery/dist/jquery.min',
// Test for Foo
'foo': 'components/app/foo/foo',
'test-Foo': 'components/app/foo/test-Foo'
},
shim: {
'QUnit': {
exports: 'QUnit',
init: function() {
QUnit.config.autoload = false;
QUnit.config.autostart = false;
}
}
}
});
require(['test-Foo'], function (Foo) {
QUnit.load();
QUnit.start();
});
test-Foo.js:
define(['foo'], function(Foo) {
'use strict';
module("Foo");
test("Foo return Test", function() {
equal(Foo.foo(), "foo", "Function should return 'foo'");
equal(Foo.oof(), "oof", "Function should return 'oof'");
});
test("Bar return Test", function() {
equal(Foo.bar(), "barz", "Function should return 'bar'");
});
});
Problem is that it all works fine when I open up the test-suite.html in my browser. Once sent to PhantomJS I get the following error:
Running "connect:server" (connect) task
Started connect web server on http://localhost:8000
Running "qunit:all" (qunit) task
Testing http://localhost:8000/qunit/qunit-test-suite.html
>> PhantomJS timed out, possibly due to a missing QUnit start() call.
Warning: 1/1 assertions failed (0ms) Use --force to continue.
Aborted due to warnings.
Full setup: https://github.com/markusfalk/test-travis
Test Run: https://travis-ci.org/markusfalk/test-travis
Thanks for any help :)
With the help of Jörn I came up with a working setup. Trick is to setup requireJS before QUnit loads (moved requireJS config to config.js and load it first).
Requirements:
grunt-contrib-qunit v0.7.0
qunit v1.18.0
HTML test suite:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>QUnit Tests Suite: asdf</title>
<link rel="stylesheet" href="../components/libs/qunit/qunit/qunit.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="config.js"></script>
<script data-main="unit" src="../components/libs/requirejs/require.js"></script>
</body>
</html>
config.js
var requirejs = {
baseUrl: "../",
paths: {
//{{app}}
'foo': 'components/app/foo/foo',
'test-foo': 'components/app/foo/test-foo',
//{{libs}}
'unit': 'qunit/unit',
'qunit': 'components/libs/qunit/qunit/qunit',
'jquery.exists': 'libs/jquery.exists/jquery.exists',
'jquery': 'components/libs/jquery/dist/jquery.min'
},
'shim': {
'jquery.exists': ['jquery']
}
};
unit.js
require([
'qunit',
'test-foo'
],
function(qunit, TestFoo) {
TestFoo();
qunit.start();
});
test-foo.js:
define(['jquery', 'qunit', 'foo'], function($, qunit, Foo) {
'use strict';
return function() {
qunit.module("Foo");
qunit.test("Foo Test", function() {
equal(Foo.saySomething(), "Hello", "returns 'Hello'");
});
};
});
And finally the module I want to test:
define(['jquery'], function($) {
'use strict';
var Foo = {
saySomething: function() {
return "Hello";
}
};
return {
saySomething: Foo.saySomething
};
});
Have you tried running grunt with the -v and/or -d flags to get some more verbose output? I did notice that there was something skipped regarding PhantomJS in your travis-ci build.
Writing location.js file
PhantomJS is already installed at /usr/local/phantomjs/bin/phantomjs.
npm WARN excluding symbolic link lib/socket.io-client.js -> io.js
If it's dependant on io.js and the link isn't there, it will fail.
UPDATE:
I found the issue using the verbose output. Your test is 404ing because of a filename issue.
["phantomjs","onResourceReceived",{"contentType":"text/html; charset=utf-8","headers":[{"name":"X-Content-Type-Options","value":"nosniff"},{"name":"Content-Type","value":"text/html; charset=utf-8"},{"name":"Content-Length","value":"43"},{"name":"Date","value":"Fri, 10 Apr 2015 06:45:47 GMT"},{"name":"Connection","value":"keep-alive"}],"id":6,"redirectURL":null,"stage":"end","status":404,"statusText":"Not Found","time":"2015-04-10T06:45:47.747Z","url":"http://localhost:10000/components/app/foo/test-Foo.js"}]
You're trying to use the file test-Foo.js. The file is named test-foo.js in your repository. Changing the case should fix the test.
Apologies in advance if I'm stating the obvious but do you have PhantomJS installed? I can't see it in your packages.json file. You can install it using npm install phantomjs --save-dev in your project root. The save-dev will add it to your packages.json so when you run npm install it will automatically get installed.
My structure looks like so:
index.html
main.js #holds the configs.path and configs.shim
libs
jquery.js
require.js
backbone.js
underscore.js
modules
app
main.js #want to load in ./views/app.js here
views
app.js
so in /modules/app/main.js, I want to load in the /modules/app/views/app.js but having problem
Here is /modules/app/main.js
define(['views/app'],function(App){
console.log('app main')
//var app = new App();
})
The console error message I get is Get failed with path GitProjects/GameApp/views/app.js
How do I get it to load relatively inside modules?
here is ./main.js the file that holds the configs
require.config({
paths: {
jquery: './libs/jquery-2.0.3',
underscore: './libs/underscore',
backbone: './libs/backbone'
},
shim: {
"underscore": {
exports: '_'
},
"backbone": {
deps: ["underscore", "jquery"],
exports: "Backbone"
}
}
});
and here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Stop Game App</title>
<script src="./libs/require.js" data-main='./main'></script>
</head>
<body>
<div id="app"></div>
<script>
require(['./modules/app/main'],function(){
console.log('main')
})
</script>
</body>
</html>
You just need to set the path to "./" and be relative. That's all there is to it.