簡體   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