我正在寻找一种方法来检查特定页面中的所有img src是否产生200.我到目前为止得到了这个脚本:
test('Check if all images exist', async t => {
var images = Selector('img');
var count = await images.count;
for(var i=0; i < count; i++) {
var url = await images.nth(i).getAttribute('src');
if(!url.startsWith('data')) {
console.log(url);
console.log(getHTTPStatus(url));
console.log(await t.navigateTo(url));
}
}
});
不能我们能够读取src属性并跳过它们,如果它们以&#34; data&#34;避免base64图像。如果我现在使用navigateTo
命令,我会在浏览器中看到该图像,但我无法执行任何其他操作。你能帮我检查一下吗?
答案 0 :(得分:2)
要检查所有图片回复是否为200状态,您可以使用TestCafe ClientFunction
:
import { Selector, ClientFunction } from 'testcafe';
fixture `fixture`
.page `https://www.google.com`;
test('Check if all images exist', async t => {
var images = Selector('img');
var count = await images.count;
var requestsCount = 0;
var statuses = [];
var getRequestResult = ClientFunction(url => {
return new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
resolve(xhr.status);
};
xhr.send(null);
});
});
for (var i = 0; i < count; i++) {
var url = await images.nth(i).getAttribute('src');
if (!url.startsWith('data')) {
requestsCount++;
statuses.push(await getRequestResult(url));
}
}
await t.expect(requestsCount).eql(statuses.length);
for (const status of statuses)
await t.expect(status).eql(200);
});
或者,您可以使用一些附加模块,例如request
来简化代码:
import { Selector, ClientFunction } from 'testcafe';
import request from 'request';
fixture `fixture`
.page `https://www.google.com`;
const getLocation = ClientFunction(() => window.location.href);
test('Check if all images exist', async t => {
var images = Selector('img');
var count = await images.count;
var location = await getLocation();
var requestPromises = [];
for (var i = 0; i < count; i++) {
var url = await images.nth(i).getAttribute('src');
if (!url.startsWith('data')) {
requestPromises.push(new Promise(resolve => {
return request(location + url, function (error, response) {
resolve(response ? response.statusCode : 0);
});
}));
}
}
var statuses = await Promise.all(requestPromises);
for (const status of statuses)
await t.expect(status).eql(200);
});