NodeJS Express | ReactJS component causes timeout error while testing a view using Mocha and ZombieJS - node.js

I have added to my Node ExpressJS app some components in ReactJS. Since I introduced these components, my tests are failing due to timeout error.
My test suites is including mocha, zombie, chai and sinon, but the first two are enough to reproduce the error.
This is the test:
// tests/home-tests.js
process.env.NODE_ENV = 'test';
var app = require('../index.js');
var Browser = require('zombie');
describe('Homepage Tests', function() {
before(function(){
server = app.listen(3002);
browser = new Browser({ site: 'http://localhost:3002' });
})
it('should render title', function(done){
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
after(function(done) {
server.close(done);
});
});
This is the layout:
// views/layouts/main.handlebars
<!doctype html>
<!--[if IE 8]> <html class="ie ie8"> <![endif]-->
<!--[if IE 9]> <html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Zombie ReactJS Test!</title>
{{{_sections.page_stylesheets}}}
</head>
<body>
{{{body}}}
{{{_sections.page_javascripts}}}
</body>
</html>
This is the view I want to test:
<h1>A test page for ReactJS</h1>
<div id="example"></div>
{{#section 'page_stylesheets'}}
<!-- ReactJS -->
<script src="https://npmcdn.com/react#15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.1/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
{{/section}}
{{#section 'page_javascripts'}}
<script type="text/babel">
ReactDOM.render(
<p>Hello, world!</p>,
document.getElementById('example')
);
</script>
{{/section}}
I have reproduced the error in this small repo.
It seems that it could be easily fixed with a timeout like it follows:
// tests/home-tests.js
// ...
it('should render title', function(done){
this.timeout(5000);
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
However, this doesn't appear to be the most suitable solution. In particular, would you be able to suggest a way to run test only after the page is fully loaded (without timeouts to be set)?
Thank you in advance

Related

Buildfire - Camera Service Returns Null for Image

In my index.html I have:
<head>
<script src="../../../scripts/buildfire.js"></script>
<script src="../../../scripts/buildfire/services/camera/camera.js"></script>
</head>
Then inside of my react app I have:
buildfire.services.camera.getPicture({}, (err, image) => {
if (err) {
console.log('error: ', err);
} else {
console.log('image: ', image);
}
})
When the function fires, half of the time the console.log of image will be null, half the time it will correctly launch the camera on my phone (testing inside of the previewer). I never run into issues where it errors. In order to get it to work I just keep restarting the previewer. It seems to be a 50/50 chance of working each time I load the previewer. Testing on an android galaxy s6.
If you create a bare bones version of the plugin, without React or any other custom code, can you reproduce the issue? If so, share the code for this bare bones example plugin. Thanks.
Update: I created a bare bones plugin that utilizes the camera, and it seems to work fine when I use it on the Previewer:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../../../scripts/buildfire.js"></script>
<script src="../../../scripts/buildfire/services/camera/camera.js"></script>
</head>
<body>
<img id="pic">
</body>
<script>
buildfire.services.camera.getPicture({},
function (err, imageData) {
console.log('error', err);
console.log('imageData', imageData);
if (imageData) {
document.getElementById("pic").src = imageData;
}
}
);
</script>
</html>

Getting Blank page on localhost:3000 while using npm along with reactjs

enter image description here
var express = require ('express');
//create our app
var app = express();
app.use(express.static('public'));
app.listen(3000,function(){
console.log('Sever is up on port 3000');
});
This is code of Server.js file.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>
</head>
<body>
<script type="text/babel" src="app.jsx"></script>
</body>
</html>
Code of index.html file
var Greeter = React.createClass({
render: function(){
return(
<div>
<h1> Howdy! </h1>
</div>
);
}
});
ReactDOM.render(
<Greeter/>,
document.getElementbyId('app')
);
Code of app.jsx file
where is error? i don't find any error.
But when I am opening http://localhost:3000, I am getting a blank page.
Am using Windows 10 and node -v 6.9.1
Any help would be highly appreciated! Thanks.
You forgot to add html element with id='app', Include this in html file, it will work.
<div id="app"></div>
There is an error in this part:
ReactDOM.render(
<Greeter/>,
document.getElementbyId('app')
);
check the spelling of getElementbyId, instead of that put this getElementById.
Try babel 5.8.23.
You forgot to put in the app HTML element.
<div id="app"></div>
Also, there's a typo in getElementById. The B should be caps.
ReactDOM.render(
<Greeter/>,
document.getElementById('app')
);
Please update a Div with id as app since React is not able find an Div with id app
<div id="app"/>
continued to the answer by #MayankShukla. Try adding script for babel transpiler to transform jsx code, include this reference:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.19.0/babel.min.js"></script>

Autobahn - Sent non-empty 'Sec-WebSocket-Protocol' header error

I am trying to build a WAMP server using NodeJS, wamp.io, and websocket.io.
Here is the server-side code :
var wsio = require('websocket.io');
var wamp = require('wamp.io');
var socketServer = wsio.listen(9000);
var wampServer = wamp.attach(socketServer);
And I am trying to test the pub-sub via browser using AutobahnJS. Here is the client-side code :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wamp Example</title>
</head>
<body>
<ul class="pages">
<li>
<button id="socket">Call</button>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://autobahn.s3.amazonaws.com/autobahnjs/latest/autobahn.min.jgz">
</script>
<script>
AUTOBAHN_DEBUG = true;
</script>
<script>
var connection = new autobahn.Connection({
url: 'ws://localhost:9000/',
realm: 'realm1'
});
console.log(connection);
connection.onopen = function (session) {
console.log(session);
// session is an instance of autobahn.Session
};
connection.onclose = function(reason, detail){
console.log(reason);
}
connection.open();
</script>
</body>
</html>
But the connection always got this error :
WebSocket connection to 'ws://localhost:9000/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
This part of code return 'unreachable'
connection.onclose = function(reason, detail){
console.log(reason);
}
Is there any code I missed?

Node.js jsdom set document root

I am trying to load local javascripts with jsdom.
Now I am wondering how I can make jsdom loading the javascripts from "__dirname/../public".
Can someone help me?
My current code is:
var fs = require('fs');
var jsdom = require('jsdom');
jsdom.defaultDocumentFeatures = {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"],
MutationEvents : '2.0',
QuerySelector : false
};
exports.test = function(req, res) {
var html = fs.readFileSync(__dirname+'/../public/html/lame.html');
var document = jsdom.jsdom(html, null, {documentRoot: __dirname+'/../public/'});
var window = document.createWindow();
window.addEventListener('load', function () {
//window.$('script').remove();
//window.$('[id]').removeAttr('id');
res.send(window.document.innerHTML);
window.close();
});
}
The simple HTML page is:
<html>
<head>
<title id="title">bum</title>
<script type="text/javascript" src="/javascripts/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/stuff.js"></script>
</head>
<body>
<h1>hello world</h1>
<h2 id="bam">XXX</h2>
</body>
</html>
I've run into the same issue and got it to work. Try these, in order:
documentRoot is not documented. The option which is documented is url. So replace documentRoot with url.
If the above is not enough, then add a base element. I've set my templates like this:
<head>
<base href="#BASE#"></base>
<!-- ... -->
</head>
where #BASE# is replaced with the same value as the one passed to url.
The solutions above are extracted from actual code in use in a test suite.

Testing NodeJS with Mocha - "Require is not defined"

I've been having trouble setting up a test framework for a NodeJS + Backbone app with the constant "require is not defined" error. I finally got it working using an in-browser test framework which picks up all of the dependencies I need and running a test.js file.
Currently, I'm only doing basic testing of my Backbone models, views, and collections. Now, I want to add in API testing but I'm back to the same "require is not defined" error. What is causing this? It's clear that I'm missing something fundamental here. I just want to add:
var request = require('supertest')
, express = require('express');
var app = express();
Snippet of test.js:
describe('Application', function(){
it("creates a global variable for the namespace", function() {
should.exist(App);
})
});
describe('Models', function() {
describe('SearchFormModel', function() {
beforeEach(function() {
this.SearchFormModel = new App.Model.SearchFormModel();
this.defaultFields = this.SearchFormModel.attributes;
})
it("created a SearchFormModel", function() {
should.exist(this.SearchFormModel);
})
it("should have 7 default fields", function() {
Object.keys(this.SearchFormModel).length.should.equal(7);
})
it("should default all fields to empty string", function() {
for (var key in this.defaultFields) {
this.defaultFields[key].should.equal("");
}
})
});
});
test-runner.html:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Title & Meta -->
<title>Frontend tests</title>
<meta charset="utf-8">
<!-- Stylesheets -->
<link rel="stylesheet" href="../node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<!-- Testing Libraries -->
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script>
// Use the expect version of chai assertions - http://chaijs.com/api/bdd
var should = chai.should();
// Tell mocha we want TDD syntax
mocha.setup('tdd');
</script>
<!-- Libs -->
<script src="../public/lib/jquery-1.8.2.min.js"></script>
<script src="../public/lib/underscore-min.js"></script>
<script src="../public/lib/backbone-min.js"></script>
<script src="../public/lib/bootstrap.min.js"></script>
<script src="../public/lib/highcharts.js"></script>
<script src="../public/lib/bootstrap-datepicker.js"></script>
<script src="../public/js/modules/exporting.js"></script>
<!-- Source files -->
<script src="../public/js/namespace.js"></script>
<script src="../public/js/jst.js"></script>
<script src="../public/js/utils.js"></script>
<script src="../public/js/models/models.js"></script>
<script src="../public/js/models/search.js"></script>
<script src="../public/js/models/plot.js"></script>
<script src="../public/js/models/search_result.js"></script>
<script src="../public/js/views/header.js"></script>
<script src="../public/js/views/plot.js"></script>
<script src="../public/js/views/list.js"></script>
<script src="../public/js/views/search.js"></script>
<script src="../public/js/router.js"></script>
<script src="../public/js/app.js"></script>
<!-- Test -->
<script src="test.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
require and commonjs only works in Node.js
If you run Browser test, then you need to code it like you'll run it in the browser. Also note that Unit Test should be done in isolation, you shouldn't need to load you app server (express) to run your test.
I'd like to point you to an easy solution from there, but there's just too many choices. Very basically, you should start running browser test in the browser by loading an html file.
Then, you'll want to automatize this and run browser test from the terminal. That's when you want to run test in PhantomJs and the likes and output browser results on the terminal. Around this, you can checkout Karma and Testem who're two browser test runner (remember here Mocha alone won't run browser test via command line).
As you're using Backbone, you might be interested in the Backbone-Boilerplate Karma + Grunt test setup as a starting point. See more on this here: https://github.com/backbone-boilerplate/backbone-boilerplate

Resources