首页 > 解决方案 > 是否可以使用 TestCafé 比较两个图像以验证确切的图像是否可用?

问题描述

在我们的项目中,图标很少。我们能否使用 TestCafe 测试这些图像/图标。

示例代码:

 <a href="www.fb.com/" class="fa fa-facebook-square"> </a>

预期结果:

我需要调用本地图像并将其与网站图像进行比较。

标签: node.jsimagetestingiconstestcafe

解决方案


我可以建议两种方法来比较网站上的图像。

一种方法是对带有图像的 DOM 元素进行截图,并使用第三方库将其与本地图像进行比较。例如,查看外观相同的库。

另一种方法是使用RequestLogger记录对图像的请求,并使用Buffer.compare()方法将响应正文与本地文件进行比较。请参阅下面说明此方法的示例:

import fs from 'fs';
import { RequestLogger } from 'testcafe';

const logger = RequestLogger('https://devexpress.github.io/testcafe/images/landing-page/banner-image.png', {
    logResponseBody:    true
});

fixture `Compare images`
    .page`https://devexpress.github.io/testcafe/`;

test
    .requestHooks(logger)
    ('Test', async t => {
        await t.expect(logger.count(record => record.response.statusCode === 200)).eql(1);

        const actualImageBuffer   = logger.requests[0].response.body;
        const expectedImageBuffer = fs.readFileSync('c:\\Tests\\images\\banner-image.png');

        await t.expect(Buffer.compare(actualImageBuff, expectedImageBuff)).eql(0);
    });

推荐阅读