Clear localstorage with Casperjs

2020-03-28 04:39发布

问题:

I'm using casperjs to do some testings of a backbonejs application using localstorage.

My problem is that I can not clear the localstorage when testing with casperjs.

I have been trying to use localStorage.clear(); at the beginning of my casper file but nothing is cleared.

回答1:

I found workaround for this problem by deleting file *.localstorage in one of the following directories:

Windows c:\Users\YOUR_USER\AppData\Local\Ofi Labs\PhantomJS\

Mac OS X: /Users/YOUR_USER/Library/Application Support/Ofi Labs/PhantomJS

Linux: /home/YOUR_USER/.local/share/data/Ofi Labs/PhantomJS



回答2:

What about running this after loading a page ?

casper.evaluate(function() {
  localStorage.clear();
}, {});


回答3:

PhantomJS does not clear the localstorage correct. localStorage.clear(); does not work (At least not reliable)

You have to delete the '.localstorage' File on the Filesystem. The fs.remove Command has to be called before you open the Page. Phantomjs locks that file while the page is open.

I did it in our Project like that:

function clearStorage() {
var fs = require('fs');
var system = require('system');
var myDomain = [I get this value from the commandline Parameter I give to CasperJS];

if(system.os.name === 'windows') {
    var userName = system.env['USERPROFILE'].split('\\')[2];
    var localstoragePath = 'C:/Users/' + userName + '/AppData/Local/Ofi Labs/PhantomJS/';
    var localStorageFilename = myDomain.replace('://', '_').replace('/', '') + '_0.localstorage';
} else {
    var userName = system.env['USER'];
    var localstoragePath = '/home/' + userName + '/.local/share/Ofi Labs/PhantomJS/';
    var localStorageFilename = myDomain.replace('://', '_') + '_0.localstorage'; //Linux does not have the last "/" so no replace needed for that
}

if(fs.exists(localstoragePath + localStorageFilename)) {
    fs.remove(localstoragePath + localStorageFilename, function(err) {
        if (err) {
            casper.echo(err);
        }
        casper.echo("File deleted successfully!");
    });
}

}