メインコンテンツへスキップ

React

ReactはインタラクティブなUIを簡単に作成できるようにします。アプリケーションの各状態に対してシンプルなビューをデザインすると、データが変更されたときに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/reactrenderメソッドを使用して、コンポーネントをテストページにアタッチします。コンポーネントを操作するには、実際のエユーザーインタラクションに近い動作をする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