Clear localstorage with Casperjs

前端 未结 3 405
温柔的废话
温柔的废话 2021-01-14 23:45

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 casperj

3条回答
  •  北海茫月
    2021-01-15 00:15

    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!");
        });
    }
    

    }

提交回复
热议问题