我正在尝试计算页面上超链接的数量并测试它们是否有效。我有能力计算所有链接并在 JavaScript 中显示计数,但我似乎无法在命令行的 Protractor 中返回该值。
根据答案更新代码:
browser.waitForAngularEnabled(false);
describe('Clicks on the correct Drupal hyperlink', function() {
it('should find all links', function () {
browser.get('file:///C:/Users/Dasman/Documents/PROTRACTOR_E2E_TESTING/TestSite.html');
let allLinks = element.all(by.tagName('a'));
allLinks.count().then(function(link_tally){
console.log('There are a total of ' + link_tally + " links on this page with proper tags.")
})
browser.sleep(2000);
// A Protracterized httpGet() promise
function httpGet(siteUrl) {
var http = require('http');
var defer = protractor.promise.defer();
http.get(siteUrl, function(response) {
var bodyString = '';
response.setEncoding('utf8');
response.on("data", function(chunk) {
bodyString += chunk;
});
response.on('end', function() {
defer.fulfill({
statusCode: response.statusCode,
bodyString: bodyString
});
});
}).on('error', function(e) {
defer.reject("Got http.get error: " + e.message);
});
return defer.promise;
}
it('should return 200 and contain proper body', function() {
httpGet(allLinks).then(function(result) {
allLinks.count().then(function(statusCode){
console.log('Status code is: ' + statusCode)
})
expect(result.statusCode).toBe(200);
expect(result.bodyString).toContain('Apache');
});
});
});
});
此外,我想“检查”链接以查看它们是否打开。有没有办法转到 URL 并单击所有链接并在单独的窗口中打开它们?或者在链接有效或具有有效 URL 时获取属性?
我最初对 id 进行 xpath 并单击链接,然后在测试运行时 - 我目视验证了。但是平均每个页面上有 15-20 个链接 - 我需要一种更加自动化的方式。
Ernst 的回答为我指出了解决方案,但它确实需要一些代码重构和封装: https://github.com/SDasman/Angular_Protractor_End2End_Tests/tree/master/LinkCheck
最佳答案
要在控制台中报告您的计数,您可以这样做:
//find all links
let linkCount = element.all(by.css('a'));
// count links, with then() resolve promise and log count result
linkCount.count().then(function(cnt){
console.log('Total links = '+cnt);
});
//here you click each of the links:
linkCount.click()
您可以在此处找到有关 count()
、then()
和 element.all()
的更多信息:http://protractortest.org/#/api
要检查您的链接的响应代码,这会有点棘手,因为 Protractor 不支持开箱即用的此类请求 (see here)。
但是,有两个 SO-Post here和 here ,它提供了一种方法。
要对其进行一一测试,您应该能够使用 getAttribute('href')
。
它会是这样的(注意:未测试,但部分复制自上面提到的两个 SO-Answers)
linkCount.each(function(elem){
elem.getAttribute('href').then(function(link){
this.httpGet("http://localhost:80").then(function(result) {
expect(result.statusCode).toBe(200);
});
});
});
// A Protracterized httpGet() promise
this.httpGet = function(siteUrl) {
var http = require('http');
var defer = protractor.promise.defer();
http.get(siteUrl, function(response) {
var bodyString = '';
response.setEncoding('utf8');
response.on("data", function(chunk) {
bodyString += chunk;
});
response.on('end', function() {
defer.fulfill({
statusCode: response.statusCode,
bodyString: bodyString
});
});
}).on('error', function(e) {
defer.reject("Got http.get error: " + e.message);
});
return defer.promise;
}
关于javascript - Protractor :计算所有超链接并在页面上测试它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47682414/