简体   繁体   中英

How to test AJAX in command line?

Suppose I have some code in JavaScript , which uses jQuery.ajax to call the server REST API.

In order to test it I would like to

  • use a dummy HTTP server, which read responses from static XML files;
  • run the JavaScript code "headless", ie without a browser;
  • run all these tests in command line.

It looks like I can use node.js with an embedded dummy HTTP server. Does it make sense? Do you know any examples of such projects (in github or somewhere)?

I have not done something like this yet to be honest but I am evaluating the following approaches:

http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/

This is really interesting, I hope this link help you get started

The main problem with using node.js for this is that it doesn't provide everything that a browser will provide … including XMLHttpRequest.

I'm in the process of developing a library (proprietary, for internal use only) that I'm trying to test with node.js.

My work around for the lack of XHR support is to use this implementation of XHR in conjunction with some Microsoft provided code to add backwards compatibility for the standard XHR to old IE .

If you are using jQuery then you'll probably need to modify it as jQuery adds its own compatibility later for old IE.

The result looks like this:

var XMLHttpRequest;

if (typeof window !== 'undefined') {
    XMLHttpRequest = window.XMLHttpRequest;
}
if (typeof XMLHttpRequest === "undefined") {
    console.log("Undefined"); (function() {
        try {
            XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        } catch(e) {}
        try {
            XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP.3.0");
        } catch(e) {}
        try {
            XMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {}
        try {
            XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
        } catch(e) {}
        //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
        if (typeof XMLHttpRequest === "undefined") {
            throw new Error("This browser does not support XMLHttpRequest.");
        }
    })();
};

Beyond that, running a simple HTTP server in your test suite is the usual approach for this sort of problem. I haven't got as far as implementing that yet and am working off an httpd running on a test server.

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