繁体   English   中英

TestCafe:检查图像

[英]TestCafe: Check for Images

我正在寻找一种方法来检查特定页面中的所有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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM