Requiring PhantomJS within a Mocha test - requirejs

I'm trying to get off the ground with mocha-phantomjs and I seem to be hitting a snag with regards to require. I was hoping other sets of eyes can see what I'm doing wrong.
$ mocha-phantomjs test/index.html
My Site
1) server should be running
Error: Script error for: webpage
http://requirejs.org/docs/errors.html#scripterror
The files in question are fairly small:
https://gist.github.com/cobaltroad/6675855
Here's the spec script in particular:
test.spec.js
describe("My Site", function() {
it("server should be running", function(done) {
require(['webpage'], function(webpage) {
var page = webpage.create();
page.open("http://localhost:8080/", function() {
var title = page.evaluate(function () {
return document.title;
});
title.should.eql('My Title');
console.log("Title: " + title);
phantom.exit();
done();
});
});
}); // server should be running
});
I've tried various forms of define/require and I haven't been able to get it quite right.

Related

selenium + nodejs + nightwatchjs and phantomjs for pdf printing after logged in

I'm still new with selenium and nodejs so please help me out here...
I have already set up the code for logging in into a site with nodejs
after successfully logged in, i have to print a page to pdf with phantom.js
browser.waitForElementPresent('#username', 1000, function() {
browser.setValue('#username', 'some_username');
browser.setValue('#password', 'some_password');
browser.click('input[type="button"]');
browser.waitForElementPresent('#agreeCB1', 15000, function() {
browser.click('#agreeCB1');
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.paperSize = {
format: 'A4'
};
ph.createPage().then(function(page) {
page.open("https://www.example.com/myaccount").then(function(status) {
page.render('./reports/myaccount.pdf').then(function() {
console.log('Page Rendered');
ph.exit();
});
});
});
});
These code suppose to print the page(myaccount page) after successful logged in but it prints the login page instead e.g. https://www.example.com/loginpage
Maybe because phantomjs creates another browser session? How can I combine these phantomjs code to existing logging code above?
Thanks for all your time!

Testing with Mocha in Node.js

I'm getting really inconsistent behavior in my terminal when console.logging inside of a test I wrote using mocha. We are running a node.js server and running socket.io. Does the console.log not go to the terminal only some of the time for some reason? I'm really confused about this behavior.
➜ tests git:(master) ✗ mocha test-chat-server.js
hello world
echo
✓ echos message (68ms)
On Connect Things Should Happen
✓ initial connection events
disconnected
i'm here
2 passing (93ms)
➜ tests git:(master) ✗ mocha test-chat-server.js
hello world
echo
✓ echos message (61ms)
On Connect Things Should Happen
✓ initial connection events
2 passing (77ms)
The difference between these two times I ran the mocha test are the console.log statements that appears in the first test run (disconnected, i'm here). They do not appear in the second test that I ran.
Edit: posting my test code in response to the comment (thank you!)
var should = require('should');
var socket = require('socket.io-client')('http://localhost:3000');
describe("echo", function () {
var server,
options ={
transports: ['websocket'],
'force new connection': true
};
it("echos message", function (done) {
var client = socket.connect("http://localhost:3000", options);
client.once("connect", function () {
client.once("echo", function (message) {
message.should.equal("Hello World");
client.disconnect();
done();
});
client.emit("echo", "Hello World");
});
done();
});
});
describe("On Connect Things Should Happen", function() {
it('initial connection events', function() {
should.exist(socket);
socket.open();
socket.compress(false).emit('an event', { some: 'data' });
socket.on('error', function() {
console.log('error');
});
socket.connect();
socket.on('disconnect', function(connection) {
console.log('disconnected');
console.log("i'm here");
});
socket.on('connect', function(connection) {
console.log('connected');
});
});
});
You are falling into the classic node async trap. Your "things should happen" test sometimes returns before the disconnect event happens and sometimes not.
You need to handle the done function the same way you do in the "echoes message" test. Punctually, it should like this:
socket.on('disconnect', function(connection) {
console.log('disconnected');
console.log("i'm here");
done()});
In general, I'm not sure how much that test makes handling all those different callbacks.

testing external api calls in node.js using mocha.js

I'm trying to write tests for my npm module, which takes care of communicating with my backend api. this module will sit inside a cordova android app, and will take care of any api calls. the issue that i'm having seems to be an understanding of mocha, but i've had a good look around the internet and can't find a solution so i turn to the masses. As an example, i have a function like
test: function() {
request.get({
url: defaultHost,
headers: {
}
}, function(err, httpResponse, body) {
if(err) {
return err;
} else {
console.log(body);
return body;
}
});
}
this works will. i'm now trying to create the test for it in mocha. the problem that i'm getting is that i have no idea how to get the return function from the .get call into the mocha test. the api returns json, so i know that i'm going to have to be doing an is equal comparison, but at the moment i can't even get it to print the results. i think the problem with is that with my other mocha tests that i can get working, they all have an argument that you pass in where as this doesn't. my current code for the test looks like this.
describe('#test', function() {
it('tests api reachability;', function() {
var test = new test();
});
});
if someone can explain what is required afterwards or even just point me in the right direction on google, that would be awesome. i'm normally pretty good at the google, but failing to find direction on this one.
I think nock will solve this issue. Let's assume you sending get request to some resource (http://domain.com/resource.json) and the tests would be like this:
var nock = require('nock');
// ...
describe('#test', function() {
beforeEach(function () {
nock('http://domain.com')
.get('resource.json')
.reply(200, {
message: 'some message'
});
});
it('tests api reachability;', function() {
var test = new test();
});
});

done method "ignored" in beforeEach in mochajs test

I have a unit test for my wrapper around a web socket client. Here is the code to the test:
describe('server', function(){
var server;
beforeEach(function(done) {
server = new Server(function() {
//try to connect to the server on the expected port
var socket = new WebSocket('ws://localhost:8081');
});
server.wss.on('connection', function(client) {
server.wss.close();
done();
});
});
describe('#server', function(){
it('starts a server on a given port', function(done) {
var test = 1;
test.should.be.ok;
});
});
});
the issue that i'm running into is that while done is called properly (if i call done a second time right after the first time, i get an error that it was called twice) it does not seem to have any effect. Namely the test will fail after two second with:
Error: timeout of 2000ms exceeded
I'm kind of new at this, so i probably missed something easy...
Thanks, olivier
As usual, once you post the question you find the answer.
The trick is to call done inside each of the tests too.
describe('server', function(){
var server;
beforeEach(function(done) {
server = new Server(function() {
//try to connect to the server on the expected port
var socket = new WebSocket('ws://localhost:8081');
});
server.wss.on('connection', function(client) {
server.wss.close();
done();
});
});
describe('#server', function(){
it('starts a server on a given port', function(done) {
var test = 1;
test.should.be.ok;
=====> done();
});
});
});

Trying to test a Node.js Server process using Mocha

Fairly new to Node.js
Made an app that runs a server process and serve files (does not use express or any frameworks), Now I'm trying to unit test it.
I'm trying to use a mocha test for that... I intended to start my server process and then run requests against it to test the expected results (stats code, body content and the likes)
However it's not working properly, all the request fail to connect to the server... I'm pretty sure that the issue is because node is juts running one process loop, the server is not running "in the background" while the queries run or possibly the server is not running yet (started ASYNC) while the request are being made ?
Anyway I was wondering what was the proper way to test this, I assume that either I need to have the server run in the background (like a forked process) and/or maybe I need to find a way to wait for the server process to be "up" first but not sure how.
Or at least recommendations on testing such server process (with Mocha or other).
Thanks.
Here is example test code (Updated since original question)
var server = new Server302('./fixture/');
var instance;
describe('Tests', function() {
before(function(done) {
instance = http.createServer(function(request, response) {
console.log(request.url);
server.serve(request, response);
}).listen(8000);
instance.on("listening", function() {
console.log("started");
done();
});
});
after(function(done){
instance.close();
console.log("stopped");
done();
});
it("Should fetch test.html", function(done) {
console.log("test1");
http.get("http://localhost:8000/", function(res) {
res.on('data', function(body) {
console.log(body)
expect(body).toEqual("test");
done();
});
})
});
It seem to Execute in order but still fails with a connection error, whereas it works when testing manually with the browser:
started
test1
․․․stopped
✖ 1 of 1 tests failed:
1) Tests Should fetch test.html:
Error: connect ECONNREFUSED
at errnoException (net.js:670:11)
at Object.afterConnect [as oncomplete] (net.js:661:19)
In your before don't call done until you get the "listening" event fired by the server.
before(function(done) {
instance = http.createServer(function(request, response) {
console.log(request.url);
server.serve(request, response);
}).listen(8000);
instance.on("listening", function() {
console.log("started");
done();
});
});
That should ensure your test connections don't start before the server is ready.
See also the documentation for server.listen
Also had to deal with the body coming in chunks, here is the final thing that works, in case that helps somebody else:
var Server302 = require('../lib/server302.js'),
http = require('http'),
assert = require("assert");
var server = new Server302('./fixture/');
var instance;
describe('Tests', function() {
before(function(done) {
instance = http.createServer(function(request, response) {
server.serve(request, response);
}).listen(8100);
instance.on("listening", function() {
done();
});
});
after(function(done) {
instance.close();
done();
});
it("Should fetch test.html", function(done) {
console.log("test1");
var body = "";
http.get({host: "localhost", port:8100, path: "/"}, function(res) {
res.on('data', function(chunk) {
// Note: it might be chunked, so need to read the whole thing.
body += chunk;
});
res.on('end', function() {
assert.ok(body.toString().indexOf("<a href='/dummy.txt'>") !== -1);
assert.equal(res.statusCode, 200);
done();
});
})
});
it("Should fetch dummy.txt", function(done) {
http.get({host: "localhost", port:8100, path: "/dummy.txt"}, function(res) {
res.on('data', function(body) {
assert.equal(res.statusCode, 200);
assert.ok(body.toString().indexOf("test") === 0);
done();
});
});
});
it("Should get 404", function(done) {
http.get({host: "localhost", port:8100, path: "/qwerty"}, function(res) {
assert.equal(res.statusCode, 404);
done();
});
});
});
Using SuperTest
Here is a full and straightforward example using SuperTest and Mocha:
var server = new Server302('./fixture/');
var request = require('supertest');
describe('Tests', function() {
it('Should fetch test.html', function(done) {
request(server)
.get('/')
.expect('test', done);
});
});
SuperTest allows you to:
Request your server using SuperAgent (much easier to use than the low level http agent).
Bound your server to an ephemeral port so there is no need to keep track of ports (you can still do it manually if needed).
Use sugary expect methods that works with Mocha (or any other test framework).

Resources