phantomjs icon indicating copy to clipboard operation
phantomjs copied to clipboard

XMLHttpRequest status is 0 when running QUnit test

Open ivoloshin opened this issue 13 years ago • 37 comments

I have the following code:

        function callXhr(method, url, data, expectedStatus, expectedStatusText, callback) {
        var xhr = new XMLHttpRequest();

        xhr.open(method, url, true);
        xhr.setRequestHeader("Authorization", make_base_auth("Admin", "Admin"));

        //Setup callback
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 ) {

                if (expectedStatus !== undefined && expectedStatusText !== undefined && expectedStatus !== null && expectedStatusText !== null) {
                    equal(xhr.status.toString() + ' : ' + xhr.statusText, expectedStatus.toString() + ' : ' + expectedStatusText, method + ': ' + url + ' (status)');
                }
                callback(xhr);
            }
        };

        try {
            xhr.send(data);
        } catch (ex) {
            ok(false, ex.toString());
            start();
        }
        ok(true, "The test framework should cause this test to pass");
    }

    asyncTest('XMLHttpRequest test', function () {
        callXhr('GET', '/UnitTest/ValidateErrorCode', null, 400, 'Bad Request', function () { start(); });
    });

This passes in every browser except PhatomJS. In PhantomJS xhr.status value is 0. This happens only when server returns error codes, like 400, 404, etc. Valid results, like 200, work fine. I need to be able to differentiate between error codes.

ivoloshin avatar Apr 02 '13 14:04 ivoloshin

So, I separated the code from QUnit. It seems that XMLHttpRequest when issued synchronisly, works okay. When async, status and statustext are 0 and blank. Here are examples to try:

        function make_base_auth(user, password) {
            var tok = user + ':' + password;
            var hash = btoa(tok);
            return "Basic " + hash;
        }

        function log(text) {
            document.write(text);
        }

        //log("loaded<br>");
        //var xhr = new XMLHttpRequest();

        //var url = "/UnitTest/ValidateErrorCode";
        //log("loading: " + url + "<br>");
        //try {
        //    xhr.open("GET", url, false);
        //    xhr.setRequestHeader("Authorization", make_base_auth("Admin", "Admin"));
        //    xhr.send(null);
        //    log("xhr.status: " + xhr.status.toString());
        //}
        //catch (ex)
        //{
        //    log("err: " + ex);
        //}

        var xhr = new XMLHttpRequest();

        var url = "/UnitTest/ValidateErrorCode";
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Authorization", make_base_auth("Admin", "Admin"));

        //Setup callback
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {

                log("Status: " + xhr.status.toString() + "<br>");
            }
        };

        try {
            log("loading: " + url + "<br>");
            xhr.send(null);
            log("No issue sending data.<br>");
        } catch (ex) {
            log("error: " + ex.toString() + "<br>");
        }

ivoloshin avatar Apr 02 '13 15:04 ivoloshin

Any chance you've tried using handlers for the more modern load, error, etc. events for the XHR? The onreadystatechange handler is really only included for historical purposes (i.e. oldIE) so it could very well be buggy.

See here for an example: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress

JamesMGreene avatar Apr 02 '13 16:04 JamesMGreene

James, just tried it.

        var xhr = new XMLHttpRequest();

        var url = "/UnitTest/ValidateErrorCode";
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Authorization", make_base_auth("Admin", "Admin"));

        //Setup callback
        //xhr.onreadystatechange = function () {
        //    if (xhr.readyState === 4) {

        //        log("Status: " + xhr.status.toString() + "<br>");
        //    }
        //};

        xhr.addEventListener("load", function () {
            log("load Status: " + xhr.status.toString() + "<br>");
        }, false);

        xhr.addEventListener("error", function () {
            log("error Status: " + xhr.status.toString() + "<br>");
        }, false);

        try {
            log("loading: " + url + "<br>");
            xhr.send(null);
            log("No issue sending data.<br>");
        } catch (ex) {
            log("error: " + ex.toString() + "<br>");
        }

It works in IE, Chrome, etc... load event fires and I get status code of 400, which is what the call returns.

In phantomjs error event fires, but the status code is 0.

Ilya

Edit: Looking at previous comments I feel I should add I'm running phantomjs 1.9.0, Windows 8 64bit.

ivoloshin avatar Apr 02 '13 17:04 ivoloshin

Dears,

I had the same issue with a slightly different config. Instead of using XHR directely, I'm using jQuery.ajax() in sync mode.

My program works fine under Chrome. However, when it is being tested using PhantomJS, the jqXHR.status is set to 0 for none-existing resources. To get 404 instead, I have added '--web-security=no' to the command line starting the test.

For more details, see 'http://stackoverflow.com/questions/15913170/phantom-js-synchronous-ajax-request-network-err-xmlhttprequest-exception-101'

Warm regards.

ouadi avatar Sep 26 '13 17:09 ouadi

I'm facing this same issue with the jquery-ujs test suite with PhantomJS 1.9.2 and QUnit 1.12.0 - I tried to turn off the --web-security flag but the failed xhr gets mangled somewhere. Here is my failing test case. There is any alternative for fixing this behavior? Let me know if I can do something else to help fixing it.

lucasmazza avatar Nov 07 '13 18:11 lucasmazza

We worked around this by using http://www.awesomium.com/

ivoloshin avatar Nov 08 '13 13:11 ivoloshin

+1, seeing this when running mocha tests as well. Seems any error status codes (400's, 500's) return a status of 0.

ghost avatar Dec 29 '13 07:12 ghost

This is still an issue. Almost 2 years old now?

ronkorving avatar Dec 15 '14 08:12 ronkorving

The problem seems to occur only when a local .js file makes a request to a server. It still happens, even with --web-security turned off. Any workarounds as for now (apart from ignoring these tests in phantom)? There seem to be no info whatsoever of the status code (or anything else, for that matters) in the whole jquery's error object...

luanpotter avatar Dec 30 '14 16:12 luanpotter

Just to make it very clear. This problem has nothing to do with JQuery. It has everything to do with Phantom's implementation of XHR. I don't use JQuery and I too have this problem. Let's try and avoid to introduce variables into this problem that are completely unrelated.

ronkorving avatar Dec 31 '14 03:12 ronkorving

I just ran into this as well - using Grunt to call Jasmine. What's odd is, my code is calling an API multiple times and it only fails for some of them. Running the Jasmine UT outside of Grunt and Phantom and it works fine. (The remote server uses CORS.)

cfjedimaster avatar Dec 31 '14 22:12 cfjedimaster

I am running into this issue as well. It comes down to phantomjs XHR request having a request.status equal to 0 when it should be a 200. XHR is a critical component, so I am unpleasantly surprised to see this issue open for this long.

@ariya are there any plans to fix this? Is it fixed in a different branch/release?

MiguelCastillo avatar Jan 16 '15 15:01 MiguelCastillo

I'm also experiencing this issue using AngularJS' $http module. The error callback is properly called, but result.status is equal to 0 instead of the expected 409.

cdroulers avatar Mar 05 '15 14:03 cdroulers

+1 seeing intermittent failed XHR requests when a local file attempts to POST to a remote server.

rawberg avatar May 13 '15 07:05 rawberg

I was able to resolve this for my particular use case by overriding all XHR POST requests to execute synchronously.

var openOriginal = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    if(arguments[0] === "POST") {
        arguments[2] = false;
    }
    return openOriginal.apply(this, arguments);
};
var script = document.createElement("script");
script.src = "file:///your-local-file.js";
script.type = "application/javascript";
script.async = false;
document.getElementsByTagName("head")[0].appendChild(script);

rawberg avatar May 13 '15 15:05 rawberg

Synchronous XHR is a bug, not a feature, and should never have been part of the spec imho. In other words, cute workaround, but rather useless in the real world.

ronkorving avatar May 17 '15 06:05 ronkorving

It also brakes all Dojo tests. Sync requests was working in phantomjs v1.9.7 and now it returns 0 in v2.0 dojo/dojo.js:322

req.getText = function(url, async, onLoad){
                var xhr = getXhr();
                xhr.open('GET', fixupUrl(url), false);
                xhr.send(null);
                if(xhr.status == 200 || (!location.host && !xhr.status)){
                    if(onLoad){
                        onLoad(xhr.responseText, async);
                    }
                }else{
                    console.log(xhr.status);//<======== here  0
                    throw makeError("xhrFailed", xhr.status);
                }
                return xhr.responseText;
            };

SergKam avatar Dec 15 '15 16:12 SergKam

Hi @SergKam .. we stumbled upon the same exact issue.. have you found any further information or workarounds in the meantime?

Hi @ariya are the developers aware of this bug? It looks like it's breaking all the synchronous xhr requests (for example used by some versions of dojo framework to load modules)

krskrs avatar Dec 31 '15 11:12 krskrs

After further testing, @ariya I can confirm that this issue is not present in v1.9.8 ... so it has been introduced in 2.0 ...

krskrs avatar Jan 05 '16 14:01 krskrs

Fixed in master.

vitallium avatar Jan 23 '16 09:01 vitallium