本文へスキップ

Preact

Preactは、同じ最新のAPIを持つReactの高速な3kB代替手段です。WebdriverIOとそのブラウザランナーを使用して、実際のブラウザでPreactコンポーネントを直接テストできます。

設定

Preactプロジェクト内にWebdriverIOを設定するには、コンポーネントテストドキュメントの手順に従ってください。ランナーオプション内でプリセットとしてpreactを選択してください。例:

// wdio.conf.js
export const config = {
// ...
runner: ['browser', {
preset: 'preact'
}],
// ...
}
情報

開発サーバーとしてViteを既に使用している場合、WebdriverIOの設定でvite.config.ts内の設定を再利用することもできます。詳細については、ランナーオプションviteConfigを参照してください。

Preactプリセットには@preact/preset-viteのインストールが必要です。また、コンポーネントをテストページにレンダリングするためにTesting Libraryを使用することをお勧めします。そのため、次の追加の依存関係をインストールする必要があります。

npm install --save-dev @testing-library/preact @preact/preset-vite

その後、次のコマンドを実行してテストを開始できます。

npx wdio run ./wdio.conf.js

テストの記述

次のPreactコンポーネントがあるとします。

./components/Component.jsx
import { h } from 'preact'
import { useState } from 'preact/hooks'

interface Props {
initialCount: number
}

export function Counter({ initialCount }: Props) {
const [count, setCount] = useState(initialCount)
const increment = () => setCount(count + 1)

return (
<div>
Current value: {count}
<button onClick={increment}>Increment</button>
</div>
)
}

テストでは、@testing-library/preactrenderメソッドを使用して、コンポーネントをテストページにアタッチします。コンポーネントと対話するには、実際のユーザー操作により近い動作をするWebdriverIOコマンドを使用することをお勧めします。例:

app.test.tsx
import { expect } from 'expect'
import { render, screen } from '@testing-library/preact'

import { Counter } from './components/PreactComponent.js'

describe('Preact Component Testing', () => {
it('should increment after "Increment" button is clicked', async () => {
const component = await $(render(<Counter initialCount={5} />))
await expect(component).toHaveText(expect.stringContaining('Current value: 5'))

const incrElem = await $(screen.getByText('Increment'))
await incrElem.click()
await expect(component).toHaveText(expect.stringContaining('Current value: 6'))
})
})

PreactのWebdriverIOコンポーネントテストスイートの完全な例は、サンプルリポジトリにあります。

ようこそ!お手伝いできることはありますか?

WebdriverIO AI Copilot