javascripthtmlbrowserbrowser-testing

Test if the page has any broken JS/CSS includes


When I move around the libraries (JS/CSS files) in a project with many HTML pages for better organization, often the pages which depend on those recently moved libraries break unless I manually update their file paths in them.

Is there any way to automatically test a page by running a headless browser and throw an error if any included JS/CSS file 404s? I looked at CasperJS, PhantomJS and few other browser testing frameworks but couldn't find what I'm seeking to do.

I know this question can be considered broad but I'm completely lost on the subject and would appreciate any pointers.


Solution

  • PhantomJS apparently offers network monitoring.

    Example (netlog.js):

    var page = require('webpage').create(),
        system = require('system'),
        address;
    
    if (system.args.length === 1) {
        console.log('Usage: netlog.js <some URL>');
        phantom.exit(1);
    } else {
        address = system.args[1];
    
        page.onResourceRequested = function (req) {
            console.log('requested: ' + JSON.stringify(req, undefined, 4));
        };
    
        page.onResourceReceived = function (res) {
            console.log('received: ' + JSON.stringify(res, undefined, 4));
        };
    
        page.open(address, function (status) {
            if (status !== 'success') {
                console.log('FAIL to load the address');
            }
            phantom.exit();
        });
    }
    

    Install phantomjs and put it on your path. Save the above code as "netlog.js" and from your commandline navigate to the folder containing netlog.js and run the command phantomjs netlog.js "http://www.example.com".