使用 jest-image-snapshot 比较图像时如何忽略 body 标签中的区域或元素?

how to ignore a region or element within the body tag when using jest-image-snapshot to compare image shots?

我解决了 jest-image-shot 和 puppeteer 存储库中的几个问题。但是,我无法为此找到合适的解决方案。 基本上,我想做的是,允许开玩笑 运行 它的 toMatchImageSnapshot 并忽略 puppeteer chrome 实例的执行页面中的某些元素或区域。

在 jest-image-shot 本身中针对此问题的任何指针或现有解决方案,或者在执行 puppeteer 期间删除该元素是解决它的唯一方法吗?

不,你想要的东西不是那么容易实现的。库 jest-image-snapshot 使用库 pixelmatch 来比较两个图像。这意味着它实际上比较图像的像素而不对文档本身执行任何逻辑。

您有三个选择:

  1. 使用failureThreshold定义可以相差多少
  2. 在截取屏幕截图之前从页面中删除元素(如您所建议的)
  3. Remove/Black图像中的元素

选项 1:使用 failureThreshold

该库有一个名为 failureThreshold built-in 的选项,它允许在比较图像时定义一个阈值。此阈值适用于整个图像,而不特定于图像的元素或部分。根据您的用例,如果您要忽略的页面部分很小并且可以接受其他较小的更改,这可能会很有用。

代码示例

it('...', async () => {
    // ...
    expect(image).toMatchImageSnapshot({
        failureThreshold: '0.01',
        failureThresholdType: 'percent'
    });
});

选项 2:从页面中删除元素

这是最简单的方法。删除要忽略的元素。如果剩余页面没有完全改变,这可能是最简单和最好的方法。

代码示例

it('...', async () => {
    const page = await browser.newPage();
    await page.goto('...');
    await page.execute(() => {
        // remove element from the DOM
        const el = document.querySelector('#element-selector');
        el.parentElement.removeChild(el);
    });
    const image = await page.screenshot();

    expect(image).toMatchImageSnapshot();
});

选项 3:Remove/Black 图像中的元素

如果选项 2 由于某种原因不可行,您还可以处理图像本身。您首先检查页面内元素的位置及其高度和重量,然后将该位置的图像部分涂黑。

要获取元素的位置和大小,您可以使用以下代码:

const [top, left, weight, height] = await page.execute(() => {
    const el = document.querySelector('#element-selector');
    const rect = element.getBoundingClientRect();
    return [rect.top, rect.left, rect.width, rect.height];
});

之后你可以在比较它们之前使用像 lwip or jimp to directly manipulate the image and paint that part of the image black (or pixelate) 这样的库。