2016-03-15 59 views
2

我在量角器中試圖實現的是獲取頁面上的所有鏈接,然後逐個查看它們以檢查是否存在路由到404頁面的鏈接。使用量角器測試頁面上有效性的所有鏈接

下面這段代碼來自我的電子郵件頁面對象,請注意我在href上調用replace,因爲我要測試的頁面上的鏈接是以下格式:https://app.perflectie.nl/something並且我想要end-to-在https://staging.perflectie.nl和我的本地主機上進行最終測試。

// Used to check for 'broken' links - links that lead to a 404 page 
Email.prototype.verifyLinkQuality = function() { 
    browser.driver.findElements(by.css('a')).then(function (elements) { 

     elements.forEach(function(el) { 
      // Change the url to the base url this tests now runs on, e.g. localhost or staging 
      el.getAttribute('href').then(function(href) { 
       var url = href.replace(/https\:\/\/app\.perflectie\.nl\//g, localhost); 

       browser.get(url); 

       browser.driver.getCurrentUrl().then(function(url) { 
        expect(url).not.toContain('/Error/'); 
        browser.navigate().back(); 
       }); 
      }); 
     }); 
    }); 
} 

如果我運行此,我收到以下錯誤消息:

Failed: Element not found in the cache - perhaps the page has changed since it was looked up 
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html 
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:59:12' 
System info: host: 'DESKTOP-QLFLPK5', ip: '169.254.82.243', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_73' 
Driver info: driver.version: unknown 

我很茫然,爲什麼這是失敗了,我會非常感謝你的幫助。

回答

2

而是來回的,這往往導致過時的元素引用錯誤原因DOM變化/重裝,我會用map()收集的所有鏈接到一個數組,然後通過一個處理它們之一。這也將會對測試的性能積極影響:

$$('a').map(function(link) { 
    return link.getAttribute("href").then(function (href) { 
     return href.replace(/https\:\/\/app\.perflectie\.nl\//g, localhost); 
    }); 
}).then(function(links) { 
    links.forEach(function(link) { 
     browser.get(link); 
     expect(browser.getCurrentUrl()).not.toContain('/Error/'); 
    }); 
}); 

注意,也沒有必要解決.getCurrentUrl()明確,因爲expect()會做隱含對我們作出的預期之前。

+0

謝謝@alecxe!很好,你也考慮到了性能。真的很感激它。 –

相關問題