0
0

playwrightで任意のapiをmock化

Last updated at Posted at 2024-08-24

TL;DR

PlaywrightのRouteクラスで指定したapiをモックすることが出来ます。
E2Eテストではサーバーエラーやタイムアウト時の挙動確認をする際に便利です。

公式の記事
https://playwright.dev/docs/api/class-route

サンプル

ここではfulfill()とabort()を使ったサンプルコードと結果を示します。

パターン1: レスポンスボディを変更

sample1.js
    // レスポンスパラメータを変更する
    await page.route("**/api/logIn", (route) => { //第一引数は任意のapiパス
      route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ //返したいパラメータをセット
          hoge: "fuga",
        }),
      });
    });

image.png

パターン2: ステータスコードを変更

sample2.js
//ステータスコード:504で返す
await page.route("**/api/logIn", (route) => route.fulfill({ status: 504 }));

image.png

パターン3: リクエストを中断

sample3.js
await page.route("**/api/logIn", (route) => {route.abort()});

image.png
abortメソッドは下記の引数を指定することが出来ます。

オプション 説明
aborted 操作が(ユーザーの行動により)中断
accessdenied ネットワーク以外のリソースへのアクセス許可が拒否
addressunreachable IPアドレスに到達できません。これは通常、指定されたホストまたはネットワークへのルートがないことを意味します
blockedbyclient クライアントがリクエストをブロック
blockedbyresponse レスポンスが満たされていない要件(例えば、'X-Frame-Options'や'Content-Security-Policy'の先祖チェック)とともに配信されたため、リクエストが失敗
connectionaborted 送信されたデータに対するACKを受信しなかった結果、接続がタイムアウト
connectionclosed 接続が閉じられた(TCP FINに相当)
connectionfailed 接続の試行が失敗
connectionrefused 接続の試行が拒否
connectionreset 接続がリセット(TCP RSTに相当)
internetdisconnected インターネット接続が失わた
namenotresolved ホスト名を解決できない
timedout 操作がタイムアウト
failed 一般的な失敗が発生
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