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;
}

輸出

click counter application

在這個示例中,當我們點選按鈕時,它將遞增計數器,並將顯示當前計數。

示例 − 模擬更改輸入

在這個示例中,我們將有一個帶有輸入欄位的 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;
}

輸出

change input

在這個示例中,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;
}

輸出

keydown event

在這個示例中,當我們在選單項上按下 Enter 鍵時,會突出顯示所選專案。

總結

React 中的 Simulate 函式用於為測試目的而向 DOM 節點分發事件。它接受諸如 eventName(事件型別)、element(DOM 節點)和可選 eventData(附加事件資料)之類的引數。在本教程中,我們探討了 React 中 Simulate 函式的用法,並提供了示例和實際應用以更好地理解。

reactjs_reference_api.htm
廣告