Running a RequireJS/WireJS app using PhantomJS - requirejs

I'm trying to execute a basic app that uses RequireJS (2.1.8), WireJS (0.10.2) and PhantomJS (1.9.2):
When running the app using PhantomJS (this is my goal), WireJS fails to load (see error below).
When running the app using Chrome, it completes properly.
Please help to point out the missing part for WireJS to run properly under PhantomJS.
Following are my app files.
1) app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SaphirJS.core</title>
<script data-main="app" src="../../../target/deps/require-0.0.1/2.1.8/require.js"> </script>
</head>
<body>
</body>
</html>
2) app.js
"use strict";
require.config({
baseUrl: ".",
packages: [
{ name: 'wire', location: '../../../target/deps/wire-0.0.1/0.10.2', main: 'wire' },
{ name: 'when', location: '../../../target/deps/when-0.0.1/2.4.1', main: 'when' },
{ name: 'meld', location: '../../../target/deps/meld-0.0.1/1.3.0', main: 'meld' }
]
});
require(["wire!wireContext"], function(wireContext) {
alert(wireContext.message);
});
3) wireContext.js
define({
message: "Hello World!"
});
4) phantom-runner.js
(function() {
'use strict';
var args = require('system').args,
timeoutRef = undefined,
timeLimit = 10000;
// arg[0]: scriptName, args[1...]: arguments
if (args.length !== 2) {
console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite]');
phantom.exit(1);
}
var url = args[1],
page = require('webpage').create();
// Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`)
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onInitialized = function() {
timeoutRef = setTimeout(function(){
console.error('Test Run Failed. Timeout Exceeded. Took longer than '+ timeLimit / 1000 +' seconds.');
phantom.exit(1);
}, timeLimit);
};
page.onAlert = function(message) {
clearTimeout(timeoutRef);
phantom.exit(0);
};
page.open(url, function(status) {
if (status !== 'success') {
console.error('Unable to access network: ' + status);
phantom.exit(1);
}
});
})();
5) The error when running the app under PhantomJS
TypeError: 'undefined' is not a function (evaluating 'Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty)')
<path-to-deps>/wire-0.0.1/0.10.2/lib/object.js:13
<path-to-deps>/require-0.0.1/2.1.8/require.js:1635
<path-to-deps>/require-0.0.1/2.1.8/require.js:871
<path-to-deps>/require-0.0.1/2.1.8/require.js:1142
<path-to-deps>/require-0.0.1/2.1.8/require.js:779
<path-to-deps>/require-0.0.1/2.1.8/require.js:1169 in callGetModule
<path-to-deps>/require-0.0.1/2.1.8/require.js:1529
<path-to-deps>/require-0.0.1/2.1.8/require.js:1656
Error: Load timeout for modules: wire!wireContext_unnormalized2
http://requirejs.org/docs/errors.html#timeout
<path-to-deps>/require-0.0.1/2.1.8/require.js:138 in defaultOnError
<path-to-deps>/require-0.0.1/2.1.8/require.js:536 in onError
<path-to-deps>/require-0.0.1/2.1.8/require.js:691 in checkLoaded
<path-to-deps>/require-0.0.1/2.1.8/require.js:710
Test Run Failed. Timeout Exceeded. Took longer than 10 seconds.

You are right, Younes. PhantomJS doesn't support Function.prototype.bind for some reason.
You can polyfill Function.prototype.bind by using either cujoJS/poly or kriskowal/es5-shim.

As mentioned in the comments to the question, the origin of this problem is the fact that PhantomJS doesn't implement 'Function.prototype.bind()' function.
As suggested by the people from PhantomJS and WireJS, the problem would be fixed using an ES5 polyfill. The implementation suggested by MDN didn't help as it is a partial implementation of the specs. The implementation included in CujoJS/PolyJS has solved my problem. Now, WireJS is happy with PhantomJS.
Hereinafter is the new version of app.js
"use strict";
require.config({
baseUrl: ".",
packages: [
{ name: 'wire', location: '../../../target/deps/wire-0.0.1/0.10.2', main: 'wire' },
{ name: 'when', location: '../../../target/deps/when-0.0.1/2.4.1', main: 'when' },
{ name: 'meld', location: '../../../target/deps/meld-0.0.1/1.3.0', main: 'meld' },
{ name: 'poly', location: '../../../target/deps/poly-0.0.1/0.5.2', main: 'poly' }
]
});
require(["poly/function", "wire!appWireContext"], function(poly, wireContext) {
alert(wireContext.message);
});
Cheers

Related

Failed to load resource: the server responded with a status of 404 (Not Found) requirejs+karma

I am facing issue to load test file from another directory to my unit test file. i am using requirejs and karma another question is it right way to load chai-http module in test scenario file project
|--service
|--abcfile.js // i want to use method implemented in this file and
test it.
|---node_modules
-- all node library like karma,chai module
|--test-main
|--test-main.js
| karma.conf.js
Karma.conf.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'requirejs'],
files: [
{pattern: 'node_modules/**/*.js', included: false},
{ pattern: 'node_modules/**/*/*.js', included: false },
'test/test-main/test-main.js',
{ pattern: 'test/test-main/*.js', included: false }
],
exclude: [
],
reporters: ['progress','html'],
htmlReporter: {
outputFile: 'test/report/units.html',
pageTitle: 'Tests',
subPageTitle: 'A sample project description'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
test-main
(function() {
var specFiles = null;
var baseUrl = '';
var requirejsCallback = null;
if (typeof window != 'undefined' && window.__karma__ != undefined) {
baseUrl = '/base';
requirejsCallback = window.__karma__.start;
specFiles = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/.*\/javascript\/*\/.+_Test\.js$/.test(file)) {
specFiles.push(file);
}
}
}
}
requirejs.config({
baseUrl: baseUrl,
paths: {
'chai': './node_modules/chai/chai',
'sinon': './node_modules/sinon/pkg/sinon',
'chaiHttp': './node_modules/chai-http/dist/chai-http',
},
deps: specFiles,
callback: requirejsCallback
});
})();
user test scenario file
define(function (chai, sinon, chaiHttp) {
var expect = chai.expect;
var service= require('/service/abcfile.js');// this is file where i want one of the function to test
chai.use(chaiHttp);
Error
Failed to load resource: the server responded with a status of 404 (Not Found)
If you want to use the CommonJS sugar you have to define your module using define(function(require, exports, module) {... and it looks to me that the path of the module currently failing should be service/abcfile' (no .js extension needed or desirable, and no leading slash). So something like this:
define(function(require, exports, module) {
var chai = require("chai");
var sinon = require("sinon");
var chaiHttp = require("chaiHttp");
var expect = chai.expect;
var service= require('service/abcfile');// this is file where i want one of the function to test
chai.use(chaiHttp);
You could omit exports and module from the callback passed to define if you end up not using them.

Events gulp-nodemon are not firing

I am currently trying to write a gulp task that allows me to serve development code up through a node webserver and use browser sync to reload the page. In doing so i'm attempting to use the events with nodemon, so for example when start event occurs, I want my gulp to log what its starting. Currently the events for gulp nodemon are not firing at all. No error is being thrown and the web server is starting. I'm not sure what I am doing wrong.
gulp.task('serve-dev', ['inject'], function(){
var isDev = true;
var nodeOptions = {
script: config.nodeServer,
delayTime: 1,
env: {
'PORT': port,
'NODE_ENV': isDev ? 'dev': 'build'
},
watch: ['server.js']
};
$.nodemon(nodeOptions)
.on('start', function(){
log('*** nodemon started');
// startBroswerSync();
})
.on('restart', function (ev){
log('*** nodemon restarted');
log('files changed on restart:\n' + ev);
})
.on('crash', function(){
log('Server Crashed for some reason');
})
.on('exit', function(){
log('Server Ended Cleanly');
})
Here is my config File:
module.exports = function() {
var client = './src/';
var temp = './.tmp/';
var server = './server.js';
var config = {
// Location of index.html
index: client + 'index.html',
// Temp folder
temp: temp,
// All of the js files to load
js: [
client + '**/*.module.js',
client + '**/*.js',
'!' + client + '**/*.spec.js'
],
// Root Folder of App(Where to find index.html etc...)
client: client,
// Where to find build Sass and CSS files
css: [temp + '*css', client + 'css/*.css'],
// All Js to Vet
alljs: [
'./src/**/*.js',
'./*js'
],
// Path to Node Server
server: server,
//Sass to Compile
sass: ['src/scss/*.scss'],
// Bower and NPM Locations
bower: {
json: require('./bower.json'),
directory: './bower_components/',
ignorePath: '../..'
},
// Node Settings
defaultPort: 7203,
nodeServer: './server.js'
};
config.getWiredepDefaultOptions = function() {
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
Completely Unrelated answer, log method was not functioning properly, thus no log statements....sorry

Error in OpenShift: "phantomjs-node: You don't have 'phantomjs' installed"

I successfully created a script using phantomjs-node in local and I would like to host on OpenShift.
The thing is when I run my script hosted, I had this strange error:
phantom stderr: execvp(): No such file or directory phantomjs-node:
You don't have 'phantomjs' installed
But as you can see, I put the dependancies in the package.json file:
"dependencies": {
"express": "~3.4.4",
"phantom": "*",
"phantomjs": "*"
},
Any suggestions?
Edit:
This is how I initialize the phantomjs script:
var options = {
port: 16000,
hostname: "127.2.149.1",
path: "/phantom_path/"
}
phantom.create(function(ph) {
visitUrl(ph, 0, 0);
}, options);
The error message You don't have 'phantomjs' installed is an internal error from the phantomjs-node module. I ran into this error myself, and I managed to fix it like this:
var phantom = require('phantom');
var options = {
path: '/usr/local/bin/'
};
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open("http://www.google.com", function (status) {
console.log("opened google? ", status);
page.evaluate(function () { return document.title; }, function (result) {
console.log('Page title is ' + result);
ph.exit();
});
});
});
}, options);
Notice the options being passed to the phantom.create() method. The path option should be the full path to the directory that contains your phantomjs binary.
Phantomjs-node is looking for Phantomjs on the PATH of your Open Shift environment and cannot find it. Look for a way to add Phantomjs on this PATH.

RequireJS replacing Node's Require method

I'm running into an issue where node's require method has been replaced by requirejs' require method. We're running a backbone app and I've set up some mocha tests. The goal was to be able to run the tests in the browser, and also use grunt-mocha-test and run them in terminal on every build with grunt-contrib-watch.
I don't fully yet understand how all these pieces fit together, so please forgive any lack of explanation, understanding.
This is the set up of one of our test files, models.js:
describe("Models", function() {
var should;
var firstModule = 'models/firstModel';
var secondModule = 'models/secondModel';
var chaiModule = 'chai';
modules = [
firstModule,
secondModule,
chaiModule
];
before(function(done) {
require(modules, function(firstModel, secondModel, chai){
FirstModel = eventModel;
SecondModel = eventDetailsModel;
should = chai.should();
done();
});
});
beforeEach(function(done) {
NewFirstModel = new FirstModel();
NewSecondModel = new SecondModel();
done();
});
describe("first model", function() {
it("should exist", function (done) {
NewFirstModel.should.exist();
done();
});
});
});
Using grunt-contrib-requirejs with these settings:
compile:
options:
baseUrl: "<%= tmpDir %>/scripts"
mainConfigFile: "<%= tmpDir %>/scripts/init.js"
name: "../../bower_components/almond/almond"
out: "<%= distDir %>/scripts/app.js"
preserveLicenseComments: false
cjsTranslate: true
wrapShim: true
uglify:
ascii_only: true
The mochaTest grunt task:
test:
options:
reporter: 'spec',
src: ['app/test/*.js']
I've got a test.html file which includes each individual test file and properly tests everything I throw at them.
However, when I run the mochaTest grunt task, which points to the same test files, I get the following error:
AssertionError: path must be a string
referring to this line in models.js:
require(modules, function(firstModel, secondModel, chai){
If I console log the require method, it comes back as RequireJS' require method. I've tried a few different things, including setting nodeRequire: require in the init.js file referenced in the requirejs config. Any clues? Thanks!!!

Module not yet loaded error with require-css plugin

I am working on some codebase where require.js and require-css is used. I am getting following error message on my browser console.
Error: Module name "../../../libs/require-css/css!views/../../stylesheets/css/modules/basicTheme" has not been loaded yet for context: _ http://requirejs.org/docs/errors.html#notloaded
My requied configuration is as below:
requirejs.config({
baseUrl: './js/',
map: {
'*': {
'css': '../../../libs/require-css/css'
}
},
paths: {
...
...
},
...
...
});
In my View, I am trying to load it as below:
define(function(require) {
"use strict";
require("css!../../../stylesheets/css/modules/basicTheme.css");
});
I am not getting why this error is getting shown. I also checked that my basicTheme.css file is getting loaded in network tab in firebug.
it is shown because your require('X') is used to load a module "synchroneously" from cache, you still need to "load" the module to the page:
define(["css!../../../stylesheets/css/modules/basicTheme.css"], function(require) {
"use strict";
require("css!../../../stylesheets/css/modules/basicTheme.css");
});
or
define(function(require) {
"use strict";
require(["css!../../../stylesheets/css/modules/basicTheme.css"], function(){
//ok now it's loaded
});
});

Resources