Да, ваш мыслительный процесс был правильным. Извлечение изображений страниц > цикл через них > извлечение HREF (или другие соответствующие теги )> проверить структуру HREF > проверить код статуса HREF . Это должно держать вас в страхе более 95% времени (, учитывая, что все соответствующие утверждения и проверки были сделаны ).
Вы можете попробовать что-то подобное ( комментарииinline ):
// Scrape all the 'img' tags from the current page:
browser.elements('css selector', 'img', (result) => {
// Loop through the images found:
result.value.forEach((image, imageIndex) => {
// Extract & check the link ('href' attribute):
browser.elementIdAttribute(image.ELEMENT, 'href', function(imgRes) {
console.info(`\n> Checking link: ${imgRes.value}`);
href = imgRes.value;
// Check the HREF returns 200 Status Code:
browser.assertHttpResponse(href, 'image/png');
// > do your link asserts/checks here <
});
});
});
Вам нужно будет создать custom_command
, чтобы проверить код состояния HTTP соответствующего изображения. Я могу вставить тот, который использую, может быть, он вам пригодится:
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Description: Asserts the response (status code & MIME type) of a HTTP request
* for the resource residing at the given URL.
* !Note: Accepted status codes: 200, 301, or 302.
* @param {string} url
* @param {string} mimeType [optional]
* @returns {{Nightwatch} this}
** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
const assert = require('chai').assert;
const request = require('superagent');
exports.command = function (url, mimeType=undefined) {
this.perform((done) => {
let allowedHttpCodes = [200, 301, 302];
// !Note: HTTP responses may vary based on ENV:
(url.includes('staging')) ? allowedHttpCodes.push(400, 401, 405) : allowedHttpCodes.push(405);
// Wait for the page to load:
this.waitForReadyState('interactive', 1);
// Issue a HTTP request for the given URL:
console.info(`\n> Launching a HTTP request for: '${url}' (allowed HTTP codes: '${allowedHttpCodes}')\n`);
request.head(`${url}`)
.end((err, res) => {
// Assert the response STATUS CODE (based on env):
console.info(`\n> Found MIME type: '${res.type}'\n`);
assert.include(allowedHttpCodes, res.statusCode, `Asserting StatusCode found: '${res.statusCode}' | Expected: ${allowedHttpCodes}`);
// If present, assert the response MIME type:
if (mimeType & res.type) {
assert.isOk([mimeType, 'text/html'].includes(res.type), `Asserting MIME type found: '${res.type}' | MIME expected: ${mimeType}`);
}
});
done();
});
return this;
};
! Примечание: Некоторые теги img
могут быть скрыты, поэтому некоторые вызовы Nightwatch API могут завершиться с ошибкой.