简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM