How to clear a browser cache in Protractor

2019-06-06 10:16发布

问题:

In one of my scenario I need to clear a browser cache. I have tried with below one but it won't work.

 browser.driver.manage().deleteAllCookies();
 browser.executeScript('window.sessionStorage.clear();');
 browser.executeScript('window.localStorage.clear();');

Can anyone help me on this?

回答1:

I use it this way:

function LoginPage() {
  this.get = function() {
        browser.get('#/Login');
        browser.executeScript('window.localStorage.clear();');
        browser.executeScript('window.sessionStorage.clear();');
        browser.driver.manage().deleteAllCookies(); 
    }
}

module.exports = new LoginPage;

then I use this function in any of my test script which every time clears out cookies, session/local storage.

var loginPage = require('.././LoginPage'); 
loginPage.get();


回答2:

First of all I suggest doing it in forked browsers which will simplify your debugging efforts

 var fork = browser.forkNewDriverInstance();
 fork.get('page1');

If you still insist on clearing everything you can restart browser

 browser.restart(); // Restart the browser clears everything (careful as it returns Promise)
 browser.restartSync(); // Same as previous but synchronous == await browser.restart()

Or even better restart fork

 fork = fork.restartSync();
 fork.get('page2'); // 'page2' gotten by restarted fork

Info: https://github.com/angular/protractor/blob/master/lib/browser.ts#L537

P.S. Not sure which parts you can't clear, but as a last resort I can suggest is incognito mode

capabilities: {
  'browserName': 'chrome',
  'chromeOptions': {
      'args': ['incognito']
  }
},

Info: https://github.com/angular/protractor/blob/master/docs/browser-setup.md#adding-chrome-specific-options