reactjs - 使用 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 测试库断言图像的宽度?
解决方案
最直接的答案是将 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-runner或Taiko。
推荐阅读
- c - 同时运行多个延迟?(C)
- asp.net-core - NET Core Web API 如何在 swagger 中添加公共标头
- android - 安卓。具有单一活动方法的 BottomNavigationView
- python - 当用户重复字母时如何显示已经猜到的?
- javascript - Next Js - Providers/getProviders() - FetchError - 下一个构建
- python - 如何排除 .dat 文件中的第一行?
- django - 如何将强化学习算法与 Firebase 集成?
- android - 如何将按钮对齐到屏幕底部?[扑]
- ms-word - 获取正在使用的 Office 版本
- android - 如何在Android中收集多个状态流