
- ReactJS 教程
- ReactJS - 首頁
- ReactJS - 簡介
- ReactJS - 路線圖
- ReactJS - 安裝
- ReactJS - 特性
- ReactJS - 優點與缺點
- ReactJS - 架構
- ReactJS - 建立 React 應用
- ReactJS - JSX
- ReactJS - 元件
- ReactJS - 巢狀元件
- ReactJS - 使用新建立的元件
- ReactJS - 元件集合
- ReactJS - 樣式
- ReactJS - 屬性 (props)
- ReactJS - 使用屬性建立元件
- ReactJS - props 驗證
- ReactJS - 建構函式
- ReactJS - 元件生命週期
- ReactJS - 事件管理
- ReactJS - 建立一個事件感知元件
- ReactJS - 在 Expense Manager APP 中引入事件
- ReactJS - 狀態管理
- ReactJS - 狀態管理 API
- ReactJS - 無狀態元件
- ReactJS - 使用 React Hooks 進行狀態管理
- ReactJS - 使用 React Hooks 進行元件生命週期管理
- ReactJS - 佈局元件
- ReactJS - 分頁
- ReactJS - Material UI
- ReactJS - Http 客戶端程式設計
- ReactJS - 表單程式設計
- ReactJS - 受控元件
- ReactJS - 非受控元件
- ReactJS - Formik
- ReactJS - 條件渲染
- ReactJS - 列表
- ReactJS - Keys
- ReactJS - 路由
- ReactJS - Redux
- ReactJS - 動畫
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - 表格
- ReactJS - 使用 Flux 管理狀態
- ReactJS - 測試
- ReactJS - CLI 命令
- ReactJS - 構建和部署
- ReactJS - 示例
- Hooks
- ReactJS - Hooks 簡介
- ReactJS - 使用 useState
- ReactJS - 使用 useEffect
- ReactJS - 使用 useContext
- ReactJS - 使用 useRef
- ReactJS - 使用 useReducer
- ReactJS - 使用 useCallback
- ReactJS - 使用 useMemo
- ReactJS - 自定義 Hooks
- ReactJS 高階
- ReactJS - 可訪問性
- ReactJS - 程式碼分割
- ReactJS - Context
- ReactJS - 錯誤邊界
- ReactJS - 轉發 Refs
- ReactJS - 片段
- ReactJS - 高階元件
- ReactJS - 與其他庫整合
- ReactJS - 效能最佳化
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - 無 ES6 ECMAScript 的 React
- ReactJS - 無 JSX 的 React
- ReactJS - 調和
- ReactJS - Refs 和 DOM
- ReactJS - 渲染 Props
- ReactJS - 靜態型別檢查
- ReactJS - 嚴格模式
- ReactJS - Web Components
- 附加概念
- ReactJS - 日期選擇器
- ReactJS - Helmet
- ReactJS - 內聯樣式
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - 輪播圖
- ReactJS - 圖示
- ReactJS - 表單元件
- ReactJS - 參考 API
- ReactJS 有用資源
- ReactJS - 快速指南
- ReactJS - 有用資源
- ReactJS - 討論
ReactJS - 模擬 Simulate()
在 React 中建立互動式使用者介面時,通常需要處理諸如點選和按鍵之類的事件。因此,React 提供了一個名為 Simulate() 的實用程式來模擬這些事件以進行測試。在本教程中,我們將介紹 Simulate 的基礎知識,並建立不同的應用程式來展示其功能。
要模擬按鈕點選,首先識別按鈕元素,然後使用 ReactTestUtils.Simulate.click()。
語法
Simulate.{eventName}( element, [eventData] )
引數
eventName − 它是模擬事件的型別,例如“click”、“change”或“keyDown”。它定義要分發的 DOM 節點事件。
element − 它是將接收模擬事件的 DOM 節點。目標元素是事件發生的位置。
[eventData] − 這是可選的。此引數定義我們選擇包含的任何其他事件資料。它取決於正在執行的事件型別。例如,我們可以為“keyDown”事件傳送有關按下鍵的資訊。
返回值
Simulate 函式不返回任何值。它用於模擬並在指定的 DOM 節點上觸發事件。其目的是為了測試目的而複製使用者互動。
讓我們看下面的例子 −
用法
// Button component <button ref={(node) => this.button = node}>Click me</button> // Simulating a click event const node = this.button; ReactTestUtils.Simulate.click(node);
此程式碼示例建立一個按鈕,並使用 Simulate.click() 模擬對其的點選。此方法可用於 React 應用程式中的任何可點選元素。
以下是 React 中使用 Simulate() 函式的示例 −
示例
示例 − 基本點選計數器應用程式
在這個示例中,我們將有一個帶有按鈕的 React 元件。我們將使用 ReactTestUtils.Simulate.click() 模擬按鈕上的點選事件。因此,此應用程式的程式碼如下所示 −
import React from 'react'; import { render } from '@testing-library/react'; import ReactTestUtils from 'react-dom/test-utils'; import './App.css' class ClickExample extends React.Component { // Click logic: Increment a counter state = { clickCount: 0, }; handleClick = () => { this.setState((prevState) => ({ clickCount: prevState.clickCount + 1, })); }; render() { return ( <div className='App'> <button className="click-button" onClick={this.handleClick}>Click me</button> <p>Click Count: {this.state.clickCount}</p> </div> ); } } // Test: Simulate a click event const { getByText } = render(<ClickExample />); const buttonNode = getByText('Click me'); ReactTestUtils.Simulate.click(buttonNode);
App.css
.click-button { background-color: #4caf50; color: white; padding: 10px 20px; font-size: 16px; cursor: pointer; border: none; border-radius: 4px; } .click-button:hover { background-color: #45a049; }
輸出

在這個示例中,當我們點選按鈕時,它將遞增計數器,並將顯示當前計數。
示例 − 模擬更改輸入
在這個示例中,我們將有一個帶有輸入欄位的 React 元件。我們將使用 ReactTestUtils 模擬輸入上的更改事件,使用 Simulate.change()。處理輸入更改邏輯包括定義當輸入值更改時應該發生什麼。因此,整個應用程式的程式碼如下所示 −
import React from 'react'; import { render } from '@testing-library/react'; import ReactTestUtils from 'react-dom/test-utils'; import './App.css' class InputExample extends React.Component { state = { inputValue: '', }; handleChange = (event) => { this.setState({ inputValue: event.target.value, }); }; render() { return ( <div className='App'> <input className="input-field" type="text" value={this.state.inputValue} onChange={this.handleChange} /> <p>Current Input Value: {this.state.inputValue}</p> </div> ); } } // Test: Simulate a change event on the input const { container } = render(<InputExample />); const inputNode = container.querySelector('input'); ReactTestUtils.Simulate.change(inputNode);
App.css
.input-field { width: 200px; padding: 10px; font-size: 16px; margin-bottom: 10px; }
輸出

在這個示例中,handleChange 方法使用輸入欄位的當前值更新元件的狀態。之後,當前輸入值將顯示在輸入欄位下方。這是一個基本的示例,我們可以根據具體需求調整邏輯。
示例 − 模擬帶有 Enter 鍵的 KeyDown 事件
在這個示例中,我們將有一個帶有輸入欄位的 React 元件。我們將使用 ReactTestUtils.Simulate.keyDown() 模擬輸入上帶有 Enter 鍵的鍵盤按下事件。因此,此應用程式的程式碼如下所示 −
import React from 'react'; import { render } from '@testing-library/react'; import ReactTestUtils from 'react-dom/test-utils'; import './App.css'; // Import the CSS file class KeyDownExample extends React.Component { // Highlight the selected item state = { selectedItem: null, }; handleKeyDown = (event) => { // Set the selected item when Enter key is pressed if (event.key === 'Enter') { this.setState({ selectedItem: event.target.innerText, }); } }; render() { return ( <div className="menu"> <div className={`menu-item ${this.state.selectedItem === 'Item 1' ? 'selected' : ''}`} onKeyDown={this.handleKeyDown} > Item 1 </div> <div className={`menu-item ${this.state.selectedItem === 'Item 2' ? 'selected' : ''}`} onKeyDown={this.handleKeyDown} > Item 2 </div> <div className={`menu-item ${this.state.selectedItem === 'Item 3' ? 'selected' : ''}`} onKeyDown={this.handleKeyDown} > Item 3 </div> </div> ); } } // Test: Simulate a key down event with Enter key const { container } = render(<KeyDownExample />); const menuNode = container.querySelector('.menu-item'); ReactTestUtils.Simulate.keyDown(menuNode, { key: 'Enter', keyCode: 13, which: 13 });
App.css
.menu { margin-left: 250px; display: flex; flex-direction: column; } .menu-item { padding: 10px; font-size: 16px; cursor: pointer; border-bottom: 1px solid #ddd; } .menu-item:last-child { border-bottom: none; } .menu-item:hover { background-color: #f5f5f5; }
輸出

在這個示例中,當我們在選單項上按下 Enter 鍵時,會突出顯示所選專案。
總結
React 中的 Simulate 函式用於為測試目的而向 DOM 節點分發事件。它接受諸如 eventName(事件型別)、element(DOM 節點)和可選 eventData(附加事件資料)之類的引數。在本教程中,我們探討了 React 中 Simulate 函式的用法,並提供了示例和實際應用以更好地理解。