API Mockingという機能がPlaywright 1.29でリリースされました。
ブラウザでアクセスしたページが、裏でJSON APIを(Ajaxだったりfetch APIだったりで)叩く際に、そのコンテンツを差し替える、というもの。
公式ドキュメントにある以下のサンプル
def handle(route):
response = route.fetch()
json = response.json()
json["message"]["big_red_dog"] = []
# Fullfill using the original response, while patching the response body
# with the given JSON object.
route.fulfill(response=response, json=json)
page.route("https://dog.ceo/api/breeds/list/all", handle)
APIモックが効くもの
page.goto("https://dog.ceo/api/breeds/list/all")
page.evaluate('() => fetch("https://dog.ceo/api/breeds/list/all")')
APIモックが効かないもの
page.request.get("https://dog.ceo/api/breeds/list/all")
あくまで、ブラウザでページアクセスする際ののバックエンドAPIをモックするための仕組みであり、PlaywrightのAPI testing (request.fetch)は対象外のようだ。
Route.fetch が内部的に request.fetchを使っており、そう簡単にrequest.fetchをモックできないという事情がありそう。