gpt4 book ai didi

reactjs - 使用 React 测试库断言图像的宽度

转载 作者:行者123 更新时间:2023-12-05 08:29:43 24 4
gpt4 key购买 nike

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

// ./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 测试库断言图像的宽度?

最佳答案

最直接的答案是将 100% 宽度定义指定为 CSS 样式,而不是使用 width 属性。 HTML Standard表示 widthheight 是表示资源像素尺寸的“有效非负整数”;您真正想要的是适合其容器的图像,这是 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 的所有边界,但我确实记得在测试与尺寸或定位相关的任何内容时遇到过问题。因此,我倾向于要么不显式测试这些东西(我更喜欢测试行为而不是表示),要么在真正的 headless 浏览器中测试它们,例如使用 jest-electron-runner 中的任何一个。或 Taiko .

关于reactjs - 使用 React 测试库断言图像的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68509102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com