• [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')
    })
  • 相关阅读:
    结构型模式のBridge桥梁模式
    创建型模式のBuilder建造者模式
    设计模式的一点思考
    创建型模式のAbstractFactory抽象工厂模式
    初试phoenix
    内网搭建git server
    nsq 学习(三)nsqlookupd
    nsq 学习(二)简单使用
    nsq 学习(一)源码安装nsq
    go学习实践-protobuf
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12810243.html
Copyright © 2020-2023  润新知