2016-03-15 63 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!很好,你也考虑到了性能。真的很感激它。 –

相关问题