Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test that a webpage returns 404/500 using PhantomJS?

I'm new at PhantomJS and Javascript and I'm working on a script that test the loading time and I would like for it to detect whether there was a error 404/500 encountered while testing it and display and message in the console.log. The code goes like this:

var page = require('webpage').create(), t, address;
t = Date.now();

var testArray =
['someURL'];

function loadTest(testURL)
{
address = testURL;
page.open(address, function (status) {
    if (status !== 'success') {
        console.log('FAIL to load the address' + address);
return;
    }

});
}

for(var i = 0; i < testArray.length; i++)
{
loadTest(testArray[i]);
t = Date.now() - t;
console.log('Testing ' + testArray[i]);
console.log('Loading time ' + t + ' msec\n');
}
phantom.exit();

Help is much appreciated. Thanks

like image 355
cloudrunner Avatar asked May 10 '12 17:05

cloudrunner


1 Answers

You might want to take a look at the onResourceReceived callback to the page object, you should be able to get what you need from there. (API docs...)

This is a bit of a contrived example, and it is going to give back the status code for every resource retrieved as part of the request, but the first one will be the page itself (i.e., as opposed to supporting JS or CSS etc.):

var page = require('webpage').create();

page.onResourceReceived = function(res) {
  if (res.stage === 'end') {
    console.log('Status code: ' + res.status);
  }
};

page.open('http://some.url/that/does-not-exist', function() {
  phantom.exit();
});

Granted, this assumes that the server is going to actually return you a 404 (as opposed to a 200 masquerading as a 404, for example) -- but something along these lines should give you what you want.

like image 133
founddrama Avatar answered Oct 20 '22 06:10

founddrama