[React Testing] Use React Testing Library to Render and Test Simple React Components

Component:

import React from 'react'

function FavoriteNumber({ min = 1, max = 9 }) {
  const [number, setNumber] = React.useState(0)
  const [numberEntered, setNumberEntered] = React.useState(false)
  function handleChange(event) {
    setNumber(Number(event.target.value))
    setNumberEntered(true)
  }
  const isValid = !numberEntered || (number >= min && number <= max)
  return (
    <div>
      <label htmlFor="favorite-number">Favorite Number</label>
      <input
        id="favorite-number"
        type="number"
        value={number}
        onChange={handleChange}
      />
      {isValid ? null : <div role="alert">The number is invalid</div>}
    </div>
  )
}

export { FavoriteNumber }

 

Test:

import React from 'react'
// extend expect object to have methods from jest-dom
import '@testing-library/jest-dom/extend-expect'
import { render } from '@testing-library/react'
import { FavoriteNumber } from '../favorite-number'

test('renders a text input with placeholder Search beer', () => {
  const { getByLabelText } = render(<FavoriteNumber />)
  const input = getByLabelText(/favorite number/i)
  expect(input).toHaveAttribute('type', 'number')
})

 

上一篇:[React Testing] Debug the DOM State During Tests using React Testing Library’s debug Function


下一篇:java-输出为文本墙时的单元测试