zoukankan      html  css  js  c++  java
  • [React Testing] Test React Component Event Handlers with fireEvent from React Testing Library

    The fireEvent utility in React Testing Library supports all the events that you regularly use in the web (change, click, etc.). Let’s see how we can test our change event handler with an input.

    Component:

    <input
            id="favorite-number"
            type="number"
            value={number}
            onChange={handleChange}
          />
          {isValid ? null : <div role="alert">The number is invalid</div>}

    As we can see, the input has a 'onChange' event, and also there is a message display when the number is outside [1, 9]

    Test:

    import React from 'react'
    // extend expect object to have methods from jest-dom
    import '@testing-library/jest-dom/extend-expect'
    import { render, fireEvent } from '@testing-library/react'
    import { FavoriteNumber } from './favorite-number'
    
    test('entering an invalid value shows an error message', () => {
      const { getByLabelText, getByRole } = render(<FavoriteNumber />)
      const input = getByLabelText(/favorite number/i)
      // fire a change event
      fireEvent.change(input, { target: { value: 10 } })
      expect(getByRole('alert')).toHaveTextContent(/the number is invalid/i)
    })
  • 相关阅读:
    JavaScript 进阶篇的学习~
    JavaScript 基础的复习~
    JVM字节码解析
    Tomcat压力测试与优化方案
    Tomcat优化
    JVM垃圾收集器
    JVM的垃圾回收机制(GC)
    JVisual VM工具使用
    jstack监控JVM线程的运行情况
    监控JVM内存使用情况
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12810314.html
Copyright © 2011-2022 走看看