跳至主要內容

React

React 可以輕鬆建立互動式使用者介面。為應用程式中的每個狀態設計簡單的視圖,當您的資料變更時,React 將有效地更新和渲染正確的元件。您可以使用 WebdriverIO 及其瀏覽器執行器在真實的瀏覽器中直接測試 React 元件。

設定

若要在您的 React 專案中設定 WebdriverIO,請依照元件測試文件中的說明操作。請務必在您的執行器選項中選擇 react 作為預設值,例如:

// wdio.conf.js
export const config = {
// ...
runner: ['browser', {
preset: 'react'
}],
// ...
}
資訊

如果您已經使用 Vite 作為開發伺服器,您也可以在 WebdriverIO 設定中重複使用 vite.config.ts 中的設定。如需更多資訊,請參閱執行器選項中的 viteConfig

React 預設值需要安裝 @vitejs/plugin-react。我們也建議使用 Testing Library 將元件渲染到測試頁面。因此,您需要安裝以下額外的相依性

npm install --save-dev @testing-library/react @vitejs/plugin-react

然後您可以執行以下命令來開始測試

npx wdio run ./wdio.conf.js

撰寫測試

假設您有以下 React 元件

./components/Component.jsx
import React, { useState } from 'react'

function App() {
const [theme, setTheme] = useState('light')

const toggleTheme = () => {
const nextTheme = theme === 'light' ? 'dark' : 'light'
setTheme(nextTheme)
}

return <button onClick={toggleTheme}>
Current theme: {theme}
</button>
}

export default App

在您的測試中,使用 @testing-library/react 中的 render 方法將元件附加到測試頁面。若要與元件互動,我們建議使用 WebdriverIO 命令,因為它們的行為更接近實際的使用者互動,例如:

app.test.tsx
import { expect } from '@wdio/globals'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

import * as matchers from '@testing-library/jest-dom/matchers'
expect.extend(matchers)

import App from './components/Component.jsx'

describe('React Component Testing', () => {
it('Test theme button toggle', async () => {
render(<App />)
const buttonEl = screen.getByText(/Current theme/i)

await $(buttonEl).click()
expect(buttonEl).toContainHTML('dark')
})
})

您可以在我們的範例儲存庫中找到 React 的 WebdriverIO 元件測試套件的完整範例。

歡迎!有什麼我可以幫你嗎?

WebdriverIO AI Copilot