Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate Jasmine-Node and express.js

I created a simple Webapp using express.js and want to test it with jasmine-node. Works fine so far but my problem is that I have to start the server manually every time before I can run my tests.

Could you help me on how to write a spec-helper that runs the server (with another port then my development one) just for the tests and then kills it afterwards?

like image 934
optikfluffel Avatar asked Nov 01 '12 11:11

optikfluffel


1 Answers

This is what I do:

I have a server.js file inside the root of my node project that sets up the node application server (with express) and exports 2 methods:

exports.start = function( config, readyCallback ) {

    if(!this.server) {

        this.server = app.listen( config.port, function() {

            console.log('Server running on port %d in %s mode', config.port, app.settings.env);

            // callback to call when the server is ready
            if(readyCallback) {
                readyCallback();
            }
        });
    }
};

exports.close = function() {
    this.server.close();
};

The app.js file will be simple at this point:

var server = require('./server');
server.start( { port: 8000 } );

So the files/folder basic structure would be the following:

src
   app.js
   server.js

Having this separation will allow you to run the server normally:

node src/app.js

..and/or require it from a custom node script, which could be a node script (or a jake/grunt/whatever task) that executes your tests like this:

/** my-test-task.js */

// util that spawns a child process
var spawn = require('child_process').spawn;

// reference to our node application server
var server = require('./path/to/server.js');

// starts the server
server.start( { port: 8000 }, function() {

    // on server ready launch the jasmine-node process with your test file
    var jasmineNode = spawn('jasmine-node', [ '.path/to/test/file.js' ]);

    // logs process stdout/stderr to the console
    function logToConsole(data) {
        console.log(String(data));
    }
    jasmineNode.stdout.on('data', logToConsole);
    jasmineNode.stderr.on('data', logToConsole);

    jasmineNode.on('exit', function(exitCode) {
        // when jasmine-node is done, shuts down the application server
        server.close();
    }
});
like image 128
BFil Avatar answered Nov 07 '22 19:11

BFil