在具有IMG元素的React组件上使用Screen.debug()时
我正在测试一个react/typescript组件,其中包含图像标签,并想知道为什么在运行screet.debug()
时,输出显示源为src =“ [[对象对象]“
。
这是我正在测试的组件:
import { useState } from 'react'
import { InfoType } from '../../constants'
type Props = {
type: InfoType
}
const HelpWidget = ({ type }: Props) => {
const [isHover, setHover] = useState<boolean>(false)
return (
<div className="help-widget">
<img
role="image"
src={require('../../../public/images/info.svg')}
onMouseEnter={() => setHover(true)}
onMouseOut={() => setHover(false)}
onClick={() => setHover(!isHover)}
/>
{isHover ? <div className="info">{type}</div> : <div role='hello'></div>}
</div>
)
}
export default HelpWidget
这是我在运行测试时收到的输出:
<body>
<div>
<div
class="help-widget"
>
<img
role="image"
src="[object Object]"
/>
<div
role="hello"
/>
</div>
</div>
</body>
我假设这可能与源属性是JSX中的JS表达式有关的事实,但不能完全确定是这种情况。
I am testing a React/Typescript component that has an image tag inside of it and wondering why, when running screen.debug()
, the output shows the source being src="[object Object]"
.
Here is the component I am testing:
import { useState } from 'react'
import { InfoType } from '../../constants'
type Props = {
type: InfoType
}
const HelpWidget = ({ type }: Props) => {
const [isHover, setHover] = useState<boolean>(false)
return (
<div className="help-widget">
<img
role="image"
src={require('../../../public/images/info.svg')}
onMouseEnter={() => setHover(true)}
onMouseOut={() => setHover(false)}
onClick={() => setHover(!isHover)}
/>
{isHover ? <div className="info">{type}</div> : <div role='hello'></div>}
</div>
)
}
export default HelpWidget
And here is the output I receive when running the test:
<body>
<div>
<div
class="help-widget"
>
<img
role="image"
src="[object Object]"
/>
<div
role="hello"
/>
</div>
</div>
</body>
I am assuming that it may have to do with the fact that the source attribute is a JS expression within JSX but not entirely sure that is the case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
序列化对象时,这是JavaScript的默认行为。这是一个更好的答案,说明这是如何/为什么发生 https://stackoverflow.com/a/a/a/25419538/3088146
这仅发生在反应测试库的背景下,这可能是因为用于构建应用程序的构建工具将其解析到字符串中,但不在反应测试图中
it's JavaScript's default behavior when serializing an object. Here is a much better answer to how/why this happens https://stackoverflow.com/a/25419538/3088146
If this only happens in the context of react-testing-library it could be because of a build tool used to build the app that properly resolves it to the string but does not in react-testing-library