reactjs 如何检查一个元素中是否有多个文本内容?

oyxsuwqo  于 2023-02-15  发布在  React
关注(0)|答案(1)|浏览(91)

我有这样一个组件:

export const MyComponent = props => {
    return (
        {
            props.options.map(option =>
                <>
                    <div>
                        <input type="radio" id={option.id} name="group" value={option.id} />
                        <label htmlFor={option.id}>{option.label}</label>
                    </div>
                    <span>Some other text</span>
                </>
            )
        }
    )
}

在我的测试中,我希望确保所有单选按钮都使用正确的标签文本呈现,并且span中的额外文本存在。

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

describe('MyComponent', () => {
    const props = {
        options: [
            { id: 1, label: 'Apple' },
            { id: 2, label: 'Banana' },
            { id: 3, label: 'Cherry' },
        ]
    }

    it('Renders the component', () => {
        render(<MyComponent {...props} />)
        
        const options = screen.queryAllByRole('radio')
        expect(options).toBeArrayOfSize(3)

        options.forEach((option, index) => {
            const { getByText } = within(option)
            expect(getByText(props.options[index])).toBeInTheDocument() // Assertion fails
            expect(getByText("Some other text")).toBeInTheDocument() // Also fails
        })
    })
})

但是,我在两个expectAssert上遇到了错误。

dw1jzc5e

dw1jzc5e1#

您可以尝试以下操作:

import { render, screen } from "@testing-library/react"
import { MyComponent } from "./MyComponent"

describe("MyComponent", () => {
  const props = {
    options: [
      { id: 1, label: "Apple" },
      { id: 2, label: "Banana" },
      { id: 3, label: "Cherry" },
    ],
  }

  it("Renders the component", () => {
    render(<MyComponent {...props} />)

    const options = screen.queryAllByRole("radio")
    expect(options).toHaveLength(3)

    props.options.forEach((option) => {
      const label = screen.getByLabelText(option.label)
      const radioBtn = screen.getByRole("radio", { name: option.label })

      // Need to use getAllByText query since the string "Some other text" is repeated... getByText will throw because of multiple matches
      const [someOtherText] = screen.getAllByText("Some other text")

      expect(label).toBeInTheDocument()
      expect(radioBtn).toBeInTheDocument()
      expect(someOtherText).toHaveTextContent(someOtherText.textContent)
    })
  })
})

相关问题