How to Use CasperJS in node.js?-open source projects n1k0/casperjs

a paid nerd

One solution (which worked for me) is to start and stop your server on a per-test basis. For example, I have a runtests.coffee which looks like:

http = require 'http'
glob = require 'glob'
spawn = require('child_process').spawn

db = require './db' # Contains all database stuff.
webapp = require './webapp' # Contains all of the Express stuff.

db.connect 'test' # Connects to the db server and creates an empty test db.
server = http.createServer webapp.makeApp()
server.listen 0, ->
    port = server.address().port
    process.env.URL = "http://localhost:#{ port }"
    glob 'tests/*', (err, filenames) ->
        child = spawn 'casperjs', ['test'].concat(filenames)
        child.stdout.on 'data', (msg) -> process.stdout.write msg
        child.stderr.on 'data', (msg) -> process.stderr.write msg
        child.on 'exit', (code) ->
            db.disconnect() # Drops the test db.
            server.close()
            process.exit code

And my CasperJS tests in tests/ look like:

URL = require('system').env.URL # Note, Casper code here, not Node.

casper.test.begin 'Test something', 1, (test) ->
    casper.start "#{ URL }/welcome"
    casper.then ->
        test.assertHttpStatus 200
        # ....
    casper.run ->
        test.done()