【问题标题】:How to properly write a test in jest library for react component?如何在 jest 库中为 React 组件正确编写测试?
【发布时间】:2022-11-17 01:14:31
【问题描述】:

我有一个简单的反应组件来渲染看起来像这样的图像:

import { string } from "prop-types"
import * as Styled from "./Image.styled"

const Image = ({ Src, Alt }) => <Styled.Image src={Src} alt={Alt} />

Image.propTypes = {
  Alt: string,
  Src: string,
}

Image.defaultProps = {
  Alt: null,
  Src: null,
}
export default Image

对于这个,我想写一个测试来检查 src 和 Alt 是否会正确呈现。 我试着写这样的东西:

import { render, screen } from "../../../test-utils"

import Image from "../Image"

const src ="https://images.pexels.com/photos/39317/chihuahua-dog-puppy-cute-39317.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
const alt = "dog"

describe(`Image`, () => {
  it(`renders Image with default properties`, () => {
    render(<Image src={src} alt={alt} />)
    expect(screen.getByText(Image)).toBeInTheDocument()
  })
})

但它失败了。终端说它在方法行上,所以知道哪个更好吗?

【问题讨论】:

  • 你的测试没有意义。你没有传递正确的道具,你正在使用组件来尝试选择自己作为文本?!此外,没有理由至少为 Src 道具设置默认值,当然不是 null。

标签: reactjs jestjs


【解决方案1】:

尝试像这样更新您的测试(检查外壳的属性):

describe('Image', () => {
  it('renders Image with default properties', () => {
    render(<Image Src={src} Alt={alt} />);
    expect(screen.getByAltText(alt)).toBeInTheDocument();
  })
})

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2021-07-02
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多