0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Playwrightを対話形式で実行したい

Posted at

Playwrightのテストコードを書く際に、対話形式(REPL)でPlaywrightコードを実行できると色々調査しやすいなぁ、と思っていたところ以下のリポジトリを見つけました。

セットアップ

  1. リポジトリをクローンしてくる
    git clone https://github.com/marcusNumminen/playwrepl.ts.git
    cd playwrepl.ts
    
  2. 依存ライブラリが軒並み古いので、自分が使っている@playwright/testのバージョンに書き換えつつ、他のOSSもアップデートしておきます(npm-check-updates を使うと楽ちん)
  3. 依存ライブラリのインストール
    npm install
    
  4. playwrightで起動するchromium のインストール
    npx playwright install chromium
    
  5. 対話形式の起動(ブラウザが立ち上がり、対話形式が始まります)
    $ npm run playwrepl:node20 
    

( nodeのバージョンが20未満の場合は、npm run playwrepl)

利用方法

以下の変数が設定済みで、プロンプト上からは this.xxx で利用できます。

変数名 説明
browser 起動したブラウザに接続されているBrowser オブジェクト
context 起動したブラウザに接続されているBrowserContext オブジェクト
page 起動したブラウザに接続されているBrowserContext オブジェクト
expect アサーションのための関数。参照: https://playwright.dev/docs/test-assertions
request APIリクエストをするための関数。参照: https://playwright.dev/docs/api-testing

簡単なデモ

saucedemo.com (SauceLabから提供されているサンプルWebサイト) に対して、以下を実行していくと起動したブラウザ上で操作されていくのを確認できます。
もちろん、ブラウザを直接操作することも可能です。試行錯誤したいページまで手動で操作し、そこからlocator を試すという使い方ができます。

-> void await this.page.goto('https://www.saucedemo.com/')
-> await this.page.locator('[data-test="username"]').fill('standard_user')
-> await this.page.locator('[data-test="password"]').fill('secret_sauce')
-> await this.page.locator('[data-test="login-button"]').click();
-> await this.page.locator('.inventory_item').count()

また、.load コマンドを使うことで、外部ファイルからスクリプトを読み込み実行することもできます。

-> .load scripts/sample.mts
void await this.page.goto('https://www.saucedemo.com/')
await this.page.locator('[data-test="username"]').fill('standard_user')
await this.page.locator('[data-test="password"]').fill('secret_sauce')
await this.page.locator('[data-test="login-button"]').click();
await this.page.locator('.inventory_item').count()
... 6

実行履歴

これまでの実行履歴は、.history ファイルに保存されてます。

その他

注意点として対話形式内での import はうまくいかないようです(参照)。
とはいえ、このツールの主な利用用途しては、テストを書く際のブラウザ操作のトライ&エラーになりそうなため、あまり気にする必要はないと思います。

playwrepl.mts のファイルひとつで完結しており複雑でもないので、初期設定など自分用にカスタマイズして使うとかも有用です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?