In this tutorial, we will illustrate how we can do headless testing using nightmare.js on opeNode. Nightmare is a high-level browser automation library.
First we need to add nightmare to the project:
npm install nightmare
Then let's create a server which will have 2 routes, / giving a basic homepage and /test which will execute our test:
server.jsconst http = require("http"); const { exec } = require('child_process'); const server = http.createServer(function (req, res) { if (req.url == '/test') { runTest('nightmare', alertFinished, res); } else { res.end('homepage'); } }); server.listen(80, (err) => { if ( ! err) { console.log(`server is listening on 80`) } }); function runTest(subject, callback, res) { console.log(`Starting my ${subject} test.`); const cmd = `xvfb-run --server-args="-screen 0 1024x768x24" node test.js`; exec(cmd, (err, stdout, stderr) => { if (err) { // node couldn't execute the command res.end('not ok...'); return; } // the *entire* stdout and stderr (buffered) console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); callback(res, "my test"); }); } function alertFinished(res, title){ res.end("OK" + title); res.end("Great, finished."); }
The runTest contains all the magic to execute the nightmare test. We will get back to it later.
First, let's make a very basic test which will contact a webpage page and output its page title:
test.jsconst Nightmare = require('nightmare') const nightmare = Nightmare({ show: true }) nightmare .goto('http://example.com') .wait(1500) .evaluate(function(){ return document.title; }) .end() .then(function(title){ console.log(title); console.log('test done'); });
We can run this test by running:
node test.js
However, nightmare.js by default opens a gui-based browser and assume there is X server running. In a server without graphical server this cannot work. We can still make it work by using Xvfb, which is a virtual display server.
To do so, we will add a build script in order to install xvfb:
build.shchmod 777 /tmp apt-get update &&\ apt-get install -y libgtk2.0-0 libgconf-2-4 \ libasound2 libxtst6 libxss1 libnss3 xvfb &
and activate it via:
openode set-config BUILD_SCRIPT_PATH build.sh
And that's it, when we hit /test, it will run:
xvfb-run --server-args="-screen 0 1024x768x24" node test.js
which will run the nightmare.js test over the xvfb display server.
Added on Sun May 20 2018 16:09:01 GMT+0000 (Coordinated Universal Time)