Protractor - empty local storage

前端 未结 5 772
臣服心动
臣服心动 2020-12-03 13:30

I\'m using Protractor (with Jasmine) to test my AngulaJs application.

As result of some of my action I get some data saved in the localStorage. Now I need to test ot

5条回答
  •  佛祖请我去吃肉
    2020-12-03 13:54

    I solved this issue by checking the window.location before attempting to clear/modify sessionStorage or localStorage.

    If a page has not been loaded then window.location.hostname will equal the empty string ''. So if you get the emptystring, then don't attempt to interact with sessionStorage or localStorage.

    Here's some (ES6) code I used in my protractor suite to prevent this error. Note it's a cucumber-js After function, but it is still executed from protractor using chrome, and it demonstrates what you need to do to avoid this error:

    this.After(function(scenario) {
    
      function getWindowLocation() {
        return window.location;
      }
    
      function clearStorage() {
        window.sessionStorage.clear();
        window.localStorage.clear();
      }
    
      return browser.executeScript(getWindowLocation).then(function(location) {
        // NB If no page is loaded in the scneario then calling clearStorage will cause exception
        // so guard against this by checking hostname (If no page loaded then hostname == '')
        if (location.hostname.length > 0) {
          return browser.executeScript(clearStorage);
        }
        else {
          return Promise.resolve();
        }
      });
    });
    

提交回复
热议问题