Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing client-side javascript code with Jasmine and node.js

Given: client-side javascript code (runs in browser, uses jquery etc). Currently the code is tested with Rhino and envjs. We would like to switch to node.js. However, after some research, couldn't find any envjs-like supplementary that emulates a browser.

While running node.js "as is", even basic capabilities like alert() or window are missing.

Is there any standard bundle, similar to Rhino & envjs for node.js please?

like image 540
viebel Avatar asked Mar 01 '12 13:03

viebel


2 Answers

You could use zombie.js, which has everything you need for testing. Or you could leverage jsdom (which zombie.js uses internally) to get a DOM in node.js, and execute your tests against that DOM.

I can also recommend testling, which executes tests according to your specification in all common browsers -- the code is running in actual browsers against your service.

Here's a simple example with jsdom:

var jsdom = require("jsdom");

jsdom.env(url, ["http://code.jquery.com/jquery.min.js"], function(err, window) {
    // jQuery is at window.$
});

Instead of url above, you could have an HTML document, or fragment.

You can also load a page and fetch any external resources, instead of providing jQuery etc directly to jsdom:

var jsdom = require("jsdom").jsdom,
    doc = jsdom(markup),
    window = doc.createWindow();

// Do your stuff on window, jsdom will have fetched all the scripts referenced in the markup

Again, zombie.js uses jsdom internally and it might be a better starting point.

like image 55
Linus Thiel Avatar answered Oct 23 '22 12:10

Linus Thiel


There are two options for this

  1. Your testing browser code. Run it in the browser. Emulating the browser doesn't proof your code works, at all.
  2. Use a tool like phantom / zombie

Of course there are alternatives to this, you can extract any non-browser related code, write a unit test suite for them and run it in node. It's just JavaScript.

You can also use managed services like testling to run your browser tests for you

like image 2
Raynos Avatar answered Oct 23 '22 11:10

Raynos