首页 > 解决方案 > 使用 React 测试库断言图像的宽度

问题描述

假设我有一个简单的基于图像的组件:

// ./Figure.js

const Figure = ({src}) => (
    <img
        src={src}
        width="100%"
    />
);

我想测试它的宽度是100%.

我的测试:

// ./Figure.test.js

import Figure from './Figure'
import { render, screen } from '@testing-library/react'

describe('Figure', () => {
    const setup = () => {
        return render(
            <Figure
                src="https://src.com"
            />
        )
    }

    it('has the right width', () => {
        setup()

        const image = screen.getByAltText('alt')

        expect(image.src).toBe('https://src.com/')
        expect(image.width).toBe("100%")
    })
})

但是,这给了我一个错误:

  ● Figure › renders

    expect(received).toBe(expected) // Object.is equality

    Expected: "100%"
    Received: 0

问题:如何在不使用快照的情况下使用 React 测试库断言图像的宽度?

标签: reactjsimagejestjsreact-testing-library

解决方案


最直接的答案是将 100% 宽度定义指定为 CSS 样式,而不是使用width属性。HTML 标准表明width并且是表示资源像素尺寸的height“有效非负整数”;你真正想要的是一个适合其容器的图像,这是一个 CSS 问题。

通过这样做,您现在可以在测试中使用getComputedStyle()来验证您指定的内容并且它不会被其他任何内容覆盖。

// ./Figure.js
const Figure = ({src}) => (
    <img
        src={src}
        style="width: 100%;"
    />
);

// ./Figure.test.js
it('has the right width', () => {
    setup()

    const image = screen.getByAltText('alt')

    expect(image.src).toBe('https://src.com/')
    expect(getComputedStyle(image).width).toBe("100%")
})

扩展的答案是 Jest 在后台使用 jsdom,它本质上是一个用 javascript 编写的模拟浏览器。它的行为与浏览器非常相似,但不完全相同以便对测试有用。

我个人并不了解 jsdom 的所有边界,但我确实记得在测试与尺寸或定位相关的任何内容时遇到问题。因此,我倾向于要么不明确地测试这些东西(我更喜欢测试行为而不是演示),要么在真正的无头浏览器中测试它们,例如使用jest-electron-runnerTaiko


推荐阅读