React
ReactはインタラクティブなUIを簡単に作成できるようにします。アプリケーションの各状態に対してシンプルなビューをデザインすると、データが変更されたときにReactが適切なコンポーネントだけを効率的に更新・レンダリングします。WebdriverIOとそのブラウザランナーを使用することで、実際のブラウザでReactコンポーネントを直接テストできます。
セットアップ
Reactプロジェクト内でWebdriverIOをセットアップするには、コンポーネントテストドキュメントの手順に従ってください。ランナーオプション内でプリセットとしてreact
を選択するようにしてください。例:
// wdio.conf.js
export const config = {
// ...
runner: ['browser', {
preset: 'react'
}],
// ...
}
情報
Reactプリセットには@vitejs/plugin-react
がインストールされている必要があります。また、コンポーネントをテストページにレンダリングするためにTesting Libraryを使用することをお勧めします。そのため、次の追加の依存関係をインストールする必要があります。
- npm
- Yarn
- pnpm
npm install --save-dev @testing-library/react @vitejs/plugin-react
yarn add --dev @testing-library/react @vitejs/plugin-react
pnpm add --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コンポーネントテストスイートの完全な例は、サンプルリポジトリにあります。