TestCafe:检查图像



我正在寻找一种方法来检查来自特定页面的所有 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 属性,如果它们以"data"开头,则可以跳过它们以避免 base64 图像。如果我现在使用 navigateTo 命令,我会在浏览器中看到图像,但无法执行任何其他操作。你能帮我检查一下吗?

要检查所有图像响应是否具有 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);
});

最新更新