When teams weigh pytest vs pytest-bdd, the first thing to know is that pytest is the Python testing framework; pytest-bdd is a plugin that adds Gherkin scenarios and Python step definitions to it. They are not competing test runners. The practical choice is whether to write tests directly in Python, add a business-readable specification layer, or combine both approaches.Our recommendation: start with plain pytest for code-first tests. Add pytest-bdd where product, business, and engineering contributors will actively review examples of expected behavior. Use a hybrid when those needs coexist. A feature file is worth maintaining when it improves a real requirements conversation, not merely because it reads like English.
This pytest vs pytest-bdd comparison is for Python developers, QA automation engineers, and test leads. It uses the same shipping rule and inputs in both implementations, so differences in application behavior do not distort the comparison.
pytest discovers and executes tests, supports reusable fixtures and parametrization, and explains failures in Python assertions. Its scope extends from small unit tests to complex functional tests; it is not limited to testing individual functions.
A plain pytest test puts the setup, action, and expected result in Python. That can be an excellent specification for readers who work comfortably in code. Clear test names and explicit assertions matter more than elaborate structure.
Gherkin uses Given for an initial context, When for an action, and Then for an expected outcome. Python code still performs the work behind those sentences.
The layer changes how behavior is expressed and reviewed. It does not automatically expand coverage or remove the need to understand the application.
BDD is a workflow, not just Given/When/Then
Behavior-driven development (BDD) combines discovery, formulation, and automation: agree on concrete examples, express them clearly, and use them to guide implementation. Cucumber’s guidance emphasizes collaboration across business and technical roles.
For our shipping example, a useful discovery question is: “Does free shipping start at a subtotal of 5,000 or only above it?” Agreeing on that boundary is valuable before either test is written. Translating an existing test into Gherkin afterward does not, by itself, demonstrate that collaboration occurred.
Also requires an additional tool; reporter compatibility matters
Good starting point
Technical checks primarily maintained in code
Agreed business examples with active reviewers
Neither column describes a no-code solution. Nor does the choice determine whether a test exercises a function, an API, or a browser: that comes from the implementation behind the test.
The Same Business Rule Tested in pytest vs pytest-bdd
Example setup and expected outcomes
Illustrative example, not a client implementation. Amounts use integer minor currency units; for a two-decimal currency, 5,000 minor units represents 50.00. Our function charges no shipping fee at or above 5,000. Lower non-negative subtotals, including zero, incur a fee of 500. Negative subtotals raise ValueError with a defined message. This is a function contract, not a claim that a real checkout must accept an empty order.
All cases call the same pure function. There are no network requests, credentials, databases, retries, or shared external resources. Input-type validation and real checkout policies are outside this deliberately narrow demonstration.
Case
Input subtotal
Expected outcome
Lowest valid subtotal
0
Fee of 500
Below threshold
2,500
Fee of 500
Immediately below
4,999
Fee of 500
Exactly at threshold
5,000
Fee of 0
Immediately above
5,001
Fee of 0
Invalid negative subtotal
−1
ValueError: subtotal must be non-negative
Documented target: Python 3.12, pytest 9.2.0, and pytest-bdd 9.0.1. The pytest-bdd release fixes a pytest 9.2.0 fixture-manager compatibility issue. These are target pins, not a verified environment for this article.
Execution status, November 29, 2026: The revised plain tests were run on Linux, Python 3.13.5, and pytest 9.0.2: six collected, six passed, and six JUnit cases. The reject-zero mutation and an incorrect fee expectation each produced one expected failure; restoration returned six passes. Python 3.12, pytest-bdd, and pytest-xdist were unavailable in the execution environment, and target-package downloads failed. BDD, combined reporting, and parallel execution remain unverified. The accompanying example archive retains the logs and environment manifest.
Create the files below before installing dependencies or running tests. The example archive also supplies the optional CI requirements, report checker, and validation checklist; it is not a fully target-validated sample.
pytest.ini: register both test groups before collection
[pytest]
testpaths = tests
addopts = -ra --strict-markers
markers =
unit: direct tests of the shipping function
acceptance: business-rule scenarios implemented with pytest-bdd
shipping.py: the shared application behavior
def shipping_fee(subtotal: int) -> int:
"""Calculate shipping for an integer subtotal in minor units."""
if subtotal < 0:
raise ValueError("subtotal must be non-negative")
return 0 if subtotal >= 5_000 else 500
conftest.py: the dependency shared by both test styles
from collections.abc import Callable
import pytest
from shipping import shipping_fee
@pytest.fixture
def shipping_calculator() -> Callable[[int], int]:
return shipping_fee
Wrapping this tiny function in a fixture is intentionally educational: it makes reuse visible. A production test of a pure function could simply import it. Larger suites might inject a service client or repository through the same arrangement.
The parameter table produces five fee checks; the separate test verifies negative-input rejection. Expected fees are literal values from the agreed rule, not values calculated by repeating the implementation. pytest supports parametrized cases and exception assertions through the APIs used here.
pytest-bdd: feature files and Python step definitions
tests/bdd/features/shipping.feature
@acceptance
Feature: Shipping fees
Orders at or above 5000 minor units receive free shipping.
Lower non-negative subtotals incur a fee of 500 minor units.
Scenario Outline: Shipping fees at the threshold
Given an order subtotal of <subtotal> minor units
When the shipping fee is calculated
Then the shipping fee is <fee> minor units
Examples:
| subtotal | fee |
| 0 | 500 |
| 2500 | 500 |
| 4999 | 500 |
| 5000 | 0 |
| 5001 | 0 |
Scenario: Reject a negative subtotal
Given an order subtotal of -1 minor units
When the shipping fee is calculated
Then the calculation is rejected with "subtotal must be non-negative"
Each Examples row supplies values for the Scenario Outline. The rejection case remains separate because its expected outcome differs from a successful calculation.
tests/bdd/test_shipping_bdd.py
from collections.abc import Callable
from dataclasses import dataclass
from pytest_bdd import given, parsers, scenarios, then, when
scenarios("features/shipping.feature")
@dataclass(frozen=True)
class Result:
fee: int | None = None
error: ValueError | None = None
@given(
parsers.parse("an order subtotal of {amount:d} minor units"),
target_fixture="subtotal",
)
def order_subtotal(amount: int) -> int:
return amount
@when("the shipping fee is calculated", target_fixture="result")
def calculate_shipping(
shipping_calculator: Callable[[int], int], subtotal: int
) -> Result:
try:
return Result(fee=shipping_calculator(subtotal))
except ValueError as error:
return Result(error=error)
@then(parsers.parse("the shipping fee is {expected:d} minor units"))
def check_fee(result: Result, expected: int) -> None:
assert result.error is None
assert result.fee == expected
@then(parsers.parse('the calculation is rejected with "{message}"'))
def check_rejection(result: Result, message: str) -> None:
assert isinstance(result.error, ValueError)
assert str(result.error) == message
assert result.fee is None
The When step captures only the expected domain exception, ValueError. Unexpected exceptions are not converted into successful rejection outcomes. The positive Then checks that no error occurred; the negative Then checks the exception and confirms that no fee was produced.
Install, collect, then execute. With every file above saved, run these Bash commands from the project root on a machine with Python 3.12:
Collection should show 12 items: six per style. This is an acceptance criterion, not an observed combined result. Stop and investigate import errors, missing scenarios, or unexpected counts before running the tests. Collection does not prove that every BDD step can execute.
Each command should execute six cases: five fee calculations and one negative-subtotal rejection. Both implementations explicitly cover the valid zero boundary and the free-shipping threshold.
On Windows, create the environment with py -3.12 -m venv .venv, then use .venv\Scripts\python.exe instead of python in the installation and test commands. No shell activation is required for that form.
The pytest vs pytest-bdd contrast is now visible: the business-readable table is separated from its Python execution. For this small rule, that requires more supporting code. Whether the separation is valuable depends on who reads and maintains the feature file.
Fixtures, Test Data, and Reuse in pytest vs pytest-bdd: What Changes?
Sharing fixtures without sharing accidental state
Both implementations request shipping_calculator from the same root conftest.py. A fixture can be reused without copying its setup into every test. Function scope is pytest’s default; wider scopes deliberately extend the lifetime of a fixture instance.
For mutable scenario data, prefer a fresh object per test. Each calculation here creates a fresh, frozen Result instance rather than storing its outcome in a module-level dictionary. Isolation comes from creating a new instance; frozen=True blocks normal field assignment but does not recursively freeze referenced objects, such as the exception stored in error.
For database or API tests, assign unique test data and explicit cleanup ownership. A shared client connection and shared mutable application data are different decisions. Do not widen fixture scope simply to hide slow setup: first establish which resources can safely be reused. Use fixture teardown for resources the test creates.
Step arguments and target_fixture
A parsed step argument is not automatically a fixture available to later steps. In our Given, {amount:d} parses the number, and target_fixture="subtotal" exposes the returned value under a deliberate fixture name. The When similarly publishes result for the assertions. This is consistent with the current step APIs and execution implementation.
Keep that distinction explicit when adapting older tutorials. A later step requesting amount would not be equivalent to requesting our subtotal fixture. Use names that distinguish the input, the action result, and the expected value.
pytest.mark.parametrize versus Scenario Outline
Use pytest.mark.parametrize when the input matrix belongs naturally in Python: complex objects, technical edge conditions, or developer-owned combinations. Use a Scenario Outline when its example table is meaningful to the people reviewing the business rule. Both mechanisms create separate cases from supplied examples.
Both implementations cover the same six behaviors: five fee calculations and one negative-subtotal rejection. In the pytest vs pytest-bdd comparison, Gherkin contributes presentation and review structure, not additional coverage. In production, retain equivalent tests only when their layers or diagnostic purposes justify the duplication.
Avoid turning a feature file into a large technical dataset. Keep representative business examples readable, and place exhaustive implementation-level combinations where their owners can maintain them efficiently.
pytest vs pytest-bdd: Maintenance, Debugging, and Reporting Trade-offs
Diagnosing assertion, step-matching, and fixture failures
Rule, input, and assertion, not scenario wording alone
Test ID, actual fee, expected fee
Step definition is not found
Exact step text, parser pattern, keyword, and definition visibility
Feature path, line, unmatched text
Fixture cannot be found
Fixture name, conftest.py scope, and whether a prior step provides it
Fixture lookup traceback
A test passes alone but fails in a suite
Shared state, cleanup, and ordering assumptions
Isolated and full-suite runs with environment details
Plugin fails before tests execute
Installed versions and loaded plugin configuration
Version list and startup traceback
For an intentional assertion failure, change only the expected fee for 5,000 from 0 to 500 in the representation being checked. The application still returns 0. In the local plain-test run, this produced one failure and five passes. Restore the expectation before the next check; the corresponding BDD check still needs target-stack execution.
For a lower-boundary mutation, temporarily change the application guard from subtotal < 0 to subtotal <= 0. The new zero case must fail because zero is valid under this example’s contract. The revised plain suite detected that mutation with one failure and five passes. Restore the guard and rerun; do not leave the deliberately broken implementation in the example.
For an unmatched-step check, change only the When in “Reject a negative subtotal” to When an unsupported shipping calculation is requested. Expect one step-definition lookup failure and five passing BDD cases, then restore the text. This is a target-validation procedure, not an executed result.
JUnit XML can represent pytest results for CI consumption. pytest-bdd’s Cucumber JSON adds scenario and step information, but its reporter excludes ordinary non-BDD tests. Keep an all-suite result artifact rather than treating the BDD report as a complete suite inventory.
A readable report is not proof that the underlying rule is still correct. Give each business specification an owner, review changed expectations with that owner, and investigate scenarios that no longer match product language.
Keep steps focused on behavior rather than UI mechanics. For example, our shipping scenario describes calculating a fee, not clicking a particular button. That follows Cucumber’s guidance to separate behavior from implementation details.
Also avoid excessively generic steps such as “the operation succeeds.” Prefer an observable result that makes a failure actionable.
Why execution speed needs measurement
Do not choose a pytest vs pytest-bdd winner from the length of these examples or a single command’s runtime. A fair comparison would keep the application, inputs, assertion coverage, environment, worker count, and reporting configuration constant.
Separate collection/startup time from execution, repeat runs, and report the variation. For maintenance, record the work required to update a changed rule and diagnose a failure. These are proposed evaluation criteria, not measured advantages of either approach.
No comparative performance benchmark was performed for this article.
Running pytest and pytest-bdd Together in CI
Project layout, markers, and report artifacts
Use the directory layout and pytest.ini already created in the example setup. Run collection first, as shown there. The commands below describe a CI validation path; no hosted CI workflow or complete target-stack run was executed for this revision.
The plain module uses pytest.mark.unit; the feature uses @acceptance. By default, pytest-bdd converts tags into pytest markers. Register custom markers so --strict-markers catches unknown names.
Verify marker selection, then generate whole-suite and BDD-specific artifacts:
Expected inventory: 12 combined test items, six selected by each marker, 12 JUnit testcase elements, and six BDD JSON scenario elements. Count scenarios under each feature’s elements array, not the number of top-level features. Confirm every recorded scenario step passed; a report file alone is not evidence of complete coverage. These are target acceptance criteria.
The accompanying archive includes tools/check_reports.py. After a successful combined run, check the actual artifacts with:
The checker rejects missing, malformed, incomplete, failed, or skipped results for this sample. Its logic passed nine synthetic unit tests and checked the actual six-case plain JUnit file; it has not been exercised against a real combined BDD run. A passing report check also does not replace preserving pytest’s exit status.
In CI, preserve pytest’s exit status and upload logs and artifacts even after failure. Record python --version and python -m pip freeze --all alongside the command logs, then validate a transitive dependency lock before adopting the job as a release gate. The top-level pins below do not by themselves lock all dependencies.
Parallel execution and test isolation
Parallel execution is not a native pytest vs pytest-bdd difference; it is not built into either style. pytest-xdist is a separate plugin that can distribute pytest test items across worker processes.
For a reproducible parallel-validation candidate, the archive includes this requirements-ci.txt. Version 3.8.0 is a documented pytest-xdist release, but this combination has not been integration-tested here. Treat the pin as a validation candidate, not a “tested with” claim.
requirements-ci.txt: candidate for validation
-r requirements.txt
pytest-xdist==3.8.0
Install it in the same clean target environment, then compare serial and two-worker execution:
Require 12 passing cases and the same test identities in both XML files. The archive’s validation checklist also covers the expected Gherkin terminal-reporter rejection. That integration check remains outstanding.
Do not combine active xdist execution with --gherkin-terminal-reporter in pytest-bdd 9.0.1. Its implementation rejects that combination. This limitation concerns the Gherkin terminal reporter, not a blanket prohibition on running BDD tests in parallel.
Our shipping function has no external state. A larger suite must isolate accounts, files, database rows, and other mutable resources. pytest-xdist provides worker and run identifiers, and a session-scoped fixture is not automatically a once-only resource across all workers.
Compare serial and parallel results before enabling parallelism as a release gate. Investigate nondeterminism rather than masking it with blanket retries. Shared state and order dependence are documented sources of flaky tests.
Validate collection before expanding the suite
Use the initial --collect-only -q check before the first run and after changing bindings, markers, or example rows. A passing execution command is not enough when expected tests are missing.
Check that each intended scenario is bound once, feature paths resolve, and tags select the expected group. Keep distinct module filenames, as shown, and confirm that every Scenario Outline row is present.
Remember that --collect-only is not full validation of step execution. Follow it with a real run: a scenario can be collected yet fail when a step cannot be resolved.
pytest vs pytest-bdd: When to Choose Plain pytest, pytest-bdd, or a Hybrid
Choose plain pytest for code-first test suites
In the pytest vs pytest-bdd decision, choose plain pytest when the people maintaining the tests understand Python and most review questions concern implementation behavior, technical boundaries, or integration contracts. This is a recommendation about audience and maintenance, not a restriction on pytest’s capabilities.
For the shipping example, plain pytest is a sensible default when developers and automation engineers are the only active reviewers. Its parameter table already expresses the boundary clearly.
Add pytest-bdd for collaboratively reviewed business rules
Add pytest-bdd when feature files will be used to agree on outcomes, not merely generated after implementation. Identify who can approve changes to the shipping threshold and whether they will review the example table.
Useful adoption signals are a stable business vocabulary, recurring ambiguity about rules, and named reviewers willing to resolve it. These criteria apply the collaborative intent of BDD rather than treating Gherkin syntax as the objective.
Use a hybrid approach without rewriting everything
Start with one business rule as a limited pilot. Keep useful lower-level tests, reuse existing fixtures, and avoid a wholesale syntax conversion.
Decision question
Supports plain pytest
Supports adding pytest-bdd
Who reviews expectations?
Code-comfortable maintainers
Business and technical contributors together
Where does confusion occur?
Implementation details
Meaning of business rules and examples
Who owns the specification?
Test-code owners are sufficient
A business-rule owner will review changes
Does the extra layer help?
Python already communicates the rule clearly
The feature clarifies an otherwise difficult discussion
Can the team maintain it?
Additional bindings would be unowned
Scenario and step ownership are explicit
Continue the pilot when reviewers actually use the scenarios, disagreements are resolved earlier, and maintenance remains manageable. Stop or narrow it when feature files are ignored or merely duplicate existing tests without an additional purpose. Assess those outcomes in your own team; no universal savings percentage is justified.
The choice is not pytest or pytest-bdd. It is how much specification structure your pytest suite needs, and who will benefit from maintaining it.
Conclusion
The pytest vs pytest-bdd question is really about audience and ownership, not about which runner is better. Both styles run on pytest, share the same fixtures, and cover exactly the same six behaviors in our shipping example. Plain pytest keeps the specification in Python, while pytest-bdd adds a Gherkin layer that pays off only when real reviewers use it.
Next step: Pilot one business rule with its actual reviewers. Agree on its examples before implementing them, then keep the extra Gherkin layer only when it improves the requirements discussion and has clear maintenance ownership. If you want an experienced team to help you settle pytest vs pytest-bdd for your own suite, our automation testing services team can design, pilot, and maintain the approach with you.
Not sure whether pytest or pytest-bdd fits your test suite?
No. It adds Gherkin-based behavior tests to pytest and uses pytest's runner. The comparison is between direct Python tests and an additional specification layer.
Can pytest and pytest-bdd run in the same project?
Yes. Ordinary tests and bound scenarios can share a pytest run and suitable fixtures. Keep test selection and report coverage explicit, as the combined example demonstrates.
Do pytest-bdd tests still require Python code?
Yes. Feature files express scenarios; Python step definitions implement actions and assertions. Non-Python contributors can review the scenarios without owning every implementation detail.
Is pytest-bdd only suitable for UI testing?
No. Its steps call Python code; our illustrative example calls a function without a browser. An API or UI boundary would be a decision in the step implementation, not a requirement imposed by Gherkin.
Is pytest-bdd slower than pytest?
There is no measured winner in this article. The extra specification layer alone does not establish the practical impact on your suite. Compare equivalent workloads under the same conditions before making a performance claim.
pytest fixtures supply the data, configuration, or resources a test needs. A test requests a fixture by name; pytest resolves its dependencies, provides its value, and manages its configured lifecycle. Fixtures are therefore more than reusable setup functions: they make a test’s prerequisites and resource ownership explicit. By the end of this walkthrough of pytest fixtures, you will be able to choose fixture scope, share setup without leaking mutable state, verify cleanup after failures, and run a complete local SQLite suite. All examples use synthetic data, not client implementations.
Prerequisites: Familiarity with Python functions, imports, decorators, and assert. The inventory examples use a stock-keeping unit (SKU) as a product identifier.
Companion release v2: Complete examples and execution evidence · Browsable file index. Extract the example archive into a working folder so the referenced files remain available.
Think of a test as arrange, act, assert. A fixture handles reusable prerequisites in the arrange phase; the test performs the behavior and checks the result. A fixture might supply an empty inventory, a configured environment, or a database connection. pytest fixtures can depend on other fixtures, letting a complex prerequisite be assembled from smaller pieces.
For this tutorial, use a practical distinction: setup should establish the starting condition; assertions about the feature under test should remain visible in the test body. A failed connection during setup and an incorrect stock quantity are different problems and should be easy to distinguish.
Fixtures versus helper functions and setup methods
Prefer a fixture when pytest should manage availability, dependencies, reuse, or cleanup. Prefer an ordinary helper for a calculation or transformation with no test lifecycle to manage. A function that formats a product code does not need to become a fixture merely because several tests call it.
For new tests in this walkthrough, favor explicit fixture dependencies over a large shared setup method. This is a design recommendation, not a requirement to rewrite an existing suite. Do not call a decorated fixture as an ordinary function; request it as a parameter, or put reusable construction logic in a separate helper.
Create and Run Your First Fixture
Prepare the environment and project files
Start in the extracted pytest-fixtures-walkthrough-v2/ directory. The following project map lists every application, teaching, failure-demonstration, and verification file; the linked index also exposes every captured evidence file. Create a virtual environment with a suitable Python interpreter.
Verification matrix:
S. No
Path or version
Status for this revision
Evidence / limitation
1
pytest 9.0.2; Python 3.13.5; SQLite 3.46.1; Linux
Executed
33 application cases; 47 total; warnings-as-errors and reversed order; five lifecycle checks.
2
pytest 9.2.0; Python 3.10+ requirement
Documentation-reviewed only
Release metadata checked; package retrieval failed in this runtime. No 9.2.0 execution is claimed.
3
Other Python/OS versions; pytest-xdist
Not executed
Re-run on the intended environment before claiming compatibility or parallel safety.
Versions used: The reference release is pytest 9.2.0 (27 October 2026). The executed-version path below matches the recorded 9.0.2 runner; fresh installation was not verified here. Inspect the execution record in the companion index.
Project map (files are listed in the companion index):
Reference-version path (not executed here): Use a separate virtual environment for python -m pip install -r requirements-reference.txt, which pins pytest 9.2.0. Do not merge evidence from different environments. The archive also records the exact installed dependency versions in requirements-executed-lock.txt.
The fixture’s name matches the test parameter. pytest supplies the returned dictionary; the test does not call inventory_data(). The expected result is one passing test. Its two assertions verify both the selected item and the stock precondition.
Run commands from the project root. examples/ contains the teaching tests, tests/ exercises inventory.py, and fault_demos/ contains deliberate failures. The default suite excludes those failure demonstrations; verification tools run them separately. Copy-now labels identify complete files; excerpt labels identify fragments whose prerequisites are linked.
Share pytest Fixtures with conftest.py
Share fixtures across test modules
Use conftest.py to provide pytest fixtures to tests in its directory and descendants. Tests do not need to import these fixtures. Discovery follows the requesting test’s location; a fixture in a sibling directory is not automatically available.
Here, the override requests the parent fixture with the same name, then returns a new dictionary. The nested test asserts {"warehouse": "overflow", "currency": "INR"}. The parent test retains its original expectation. This makes the override’s boundary observable. Directory-level overrides are a supported fixture pattern.
For package scope, establish the intended Python package structure, normally with __init__.py; do not assume every folder creates a separate package lifetime. A broader-scoped connection does not require shared mutable test data. Prefer sharing expensive infrastructure while creating isolated mutable state for each test.
Understand caching and mutable state
The same fixture instance can be requested through several dependency paths without being reconstructed for each request in a test. This is reuse, not copying. Mutable values therefore remain shared by the consumers of that instance.
ready is events checks object identity. The event list proves that the dependency chain established prepared before ready. The second test checks fresh function-scoped state. Changing this list to session scope would change that isolation contract.
In the corrected example, set shared to function scope. Do not promote mutable per-test data to session scope merely to silence the error. Copy now, complete file: examples/test_corrected_scope.py.
For the SQLite example, the database fixture owns the connection; the repository object borrows it. Keeping those responsibilities separate makes the cleanup location obvious.
Excerpt, requires inventory.py and tests/conftest.py in the complete SQLite example. Protect fallible initialization immediately after acquiring the resource; this is not a separate runnable file:
Python’s finally block runs when initialization raises inside the try, including before the generator reaches yield. In this pattern, cleanup therefore covers both the setup-error path and normal fixture finalization. It cannot guarantee cleanup after a forcibly terminated process.
The alternative below registers cleanup immediately after successful acquisition. Copy now, complete file: examples/test_finalizer.py. Prerequisite:inventory.py in the complete example supplies create_schema.
import sqlite3
import pytest
from inventory import create_schema
@pytest.fixture
def finalized_db(request):
conn = sqlite3.connect(":memory:")
request.addfinalizer(conn.close)
create_schema(conn)
return conn
def test_finalized_db(finalized_db):
result = finalized_db.execute("SELECT COUNT(*) FROM inventory")
assert result.fetchone() == (0,)
For SQLite, with conn:manages a transaction; it does not close the connection. Explicit connection ownership remains necessary.
Do not treat a printed “closed” message as sufficient evidence. The lifecycle demonstration later attempts a query after closure and expects sqlite3.ProgrammingError. Its evidence marker is written only after that assertion succeeds. Avoid swallowing cleanup exceptions with except Exception: pass: a green test body must not conceal a broken teardown.
Choose Explicit Fixtures, usefixtures, or autouse
Request a value or activate setup-only behavior
An explicit parameter exposes a fixture value. usefixtures activates setup without injecting that value into the test body. Apply this marker to tests or test classes; when a fixture needs another fixture, declare the dependency in its signature.
The first test uses the returned value. The second checks the environment side effect. They illustrate different needs rather than two mandatory ways to write every test.
This fixture affects the tests in that module, not the unrelated environment-negative tests elsewhere. monkeypatch restores its environment modification afterward. Prefer an explicit fixture when the dependency is important for understanding an individual test.
S. No
Activation
Fixture value available directly?
Recommended use
1
Test parameter
Yes
A test uses the resource or configuration
2
usefixtures
No
A test needs a setup side effect only
3
autouse=True
Only if also explicitly requested
A narrowly scoped, universal test prerequisite
Parametrize Fixtures and Build Test-Data Factories
Use fixture parameters, request.param, and readable IDs
The full fixture appears below. It reads the current variant from request.param. Each dependent test runs for each fixture variant; explicit IDs make the selected resource visible in collected test names.
Two database modes combined with three quantities produce six invocations of test_add_and_read. To inspect this after creating the complete application files, run:
Each bracketed ID combines a resource mode and a quantity label. These six lines are an excerpt of the captured collection report; the timing line is omitted because this is not a benchmark.
Choose direct or indirect parametrization
Conceptual excerpt, requires the complete SQLite example. Direct parametrization sends input values straight to the test:
The test receives values such as quantities directly.
2
Configure a resource
Fixture params, or indirect parametrization
The fixture turns a mode or configuration into a usable resource.
3
Create several records in one test
Factory fixture
Call the returned builder repeatedly for independent objects.
Create several independent objects with a factory fixture
A factory fixture returns a callable rather than one finished record. Conceptual excerpt, copied from the complete tests/conftest.py: each call below returns a fresh dictionary.
The factory test creates two records, mutates the first, and checks that the second remains unchanged. It then persists both through the repository. This particular factory owns only dictionaries; the database fixture still owns persistence cleanup. For a factory that creates external resources, design cleanup for every successfully created resource, including partial-batch failures.
Use Built-in pytest Fixtures for Isolation and Evidence
Use tmp_path and tmp_path_factory
tmp_path supplies a pathlib.Path unique to a test invocation. tmp_path_factory is session-scoped and can create broader-lived temporary directories. Temporary-path isolation does not mean immediate deletion: pytest’s retention settings can preserve files from recent runs. Never put credentials in test artifacts or point --basetemp at a directory containing valuable files.
One file, shown in three labeled parts: examples/test_builtins.py. Copy all three parts into that file once. Part 1 (imports, shared seed, and private-copy test):
Treat the shared seed as read-only by convention, not as filesystem-enforced protection. The test mutates its private copy and asserts that the seed retains its content. This is the intended reuse/isolation boundary.
Control configuration with monkeypatch
Part 2, append to examples/test_builtins.py. The helper rejects missing configuration; both the negative and positive paths are explicit:
def warehouse_from_env() -> str:
value = os.getenv("WAREHOUSE")
if not value:
raise ValueError("WAREHOUSE is required")
return value
def test_missing_configuration(monkeypatch):
monkeypatch.delenv("WAREHOUSE", raising=False)
with pytest.raises(ValueError, match="WAREHOUSE is required"):
warehouse_from_env()
def test_environment_configuration(monkeypatch):
monkeypatch.setenv("WAREHOUSE", "test")
assert warehouse_from_env() == "test"
This checks the exact console output, absence of stderr, logger name, level, and message. It is more informative than checking only whether a string appeared somewhere in a combined log file. Avoid logging secrets or personal data merely to make tests easier to assert.
Build a Complete SQLite Fixture Example
Connect the application, fixtures, and tests
The minimum application uses the files below. Earlier conceptual excerpts become complete here; avoid pasting both copies into the same module. Open the complete release v2 archive or its source index.
The release also contains every earlier teaching test, failure demonstrations, both verification tools, dependency pins, and captured evidence. Run commands from the project root with python -m pytest; that invocation adds the current directory to Python’s import path.
Copy now, complete file: inventory.py
import sqlite3
MAX_QUANTITY = (1 << 63) - 1
def create_schema(conn: sqlite3.Connection) -> None:
conn.execute(
"CREATE TABLE inventory ("
"sku TEXT PRIMARY KEY NOT NULL, "
"quantity INTEGER NOT NULL CHECK(quantity >= 0))"
)
conn.commit()
class Inventory:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn
def add(self, sku: str, quantity: int) -> None:
if not isinstance(sku, str) or not sku.strip():
raise ValueError("sku must be a non-empty string")
if type(quantity) is not int or not 0 <= quantity <= MAX_QUANTITY:
raise ValueError(
f"quantity must be a non-negative integer <= {MAX_QUANTITY}"
)
with self.conn:
self.conn.execute(
"INSERT INTO inventory VALUES (?, ?)",
(sku, quantity),
)
def quantity(self, sku: str) -> int:
row = self.conn.execute(
"SELECT quantity FROM inventory WHERE sku = ?",
(sku,),
).fetchone()
if row is None:
raise KeyError(sku)
return row[0]
def count(self) -> int:
return self.conn.execute(
"SELECT COUNT(*) FROM inventory"
).fetchone()[0]
Input contract:sku must be a non-empty string. quantity must be a built-in integer from 0 through 9,223,372,036,854,775,807, inclusive (2**63 - 1 is the maximum); booleans and floats are rejected. Larger integers raise ValueError before SQL executes, rather than leaking a binding OverflowError. The range matches the non-negative portion of SQLite’s signed 64-bit INTEGER domain. Bound parameters remain in use.
Transaction baseline: The Python 3.10-compatible connect(..., isolation_level="DEFERRED") call is retained. In the executed Python 3.13 environment it uses default legacy transaction control; on Python 3.12+, isolation_level has effect only with autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL. The autocommit keyword was added in 3.12, so do not add it while promising 3.10-compatible syntax. Python recommends autocommit for new code targeting newer versions; choose and retest that policy deliberately. The connection context manager manages each write transaction, not connection closure.
The default command collects the passing test directories. Run intentional failure files only through their dedicated commands or verification harness.
Test successful operations, invalid inputs, and boundaries
The revised application run produced 33 passing cases. The maximum quantity round-trips; the first out-of-range value raises ValueError and leaves the database empty. Both checks run in memory and file mode. The duplicate test verifies that a rejected insert preserves existing data and that another insert succeeds afterward. Inspect the captured application report.
The repeated isolation test deliberately reuses "same-sku" across separate cases. Each case first asserts an empty database; it does not depend on another test running first. The factory test asserts both object independence and persisted values.
The verification matrix in the setup section defines the execution boundary. Concurrency, lock timeouts, production integration, and other database engines need separate tests when they are relevant to your application.
FIXTURE_EVIDENCE is an output-file path supplied by tools/verify_lifecycle.py. Run the command below instead of collecting this file as part of the passing suite. The harness starts each case in a fresh child process, checks exit status and JUnit phase, then inspects a fresh closure marker. It also checks the separate finalizer-failure example and scope mismatch.
python tools/verify_lifecycle.py
S. No
Scenario and precondition
Action
Expected result
Evidence checked
1
Normal setup
Query the live connection
Test passes; connection closes
Exit 0 and closure assertion marker
2
Live fixture, failing test
Trigger the assertion failure
Test fails; teardown still closes
Exit 1, failure report, closure marker
3
Connection acquired, not yet yielded
Raise during setup
Setup error; test body does not run
Exit 1, error report, closure marker
4
Finalizer already registered
Raise during later initialization
Finalizer closes the resource
Separate error report and closure marker
5
Invalid scope dependency
Request session fixture using function fixture
Setup rejected
ScopeMismatch in the report
All five lifecycle/diagnostic checks matched their expected outcomes. One child passes; the intentional assertion failure and three setup/scope errors remain negative outcomes. The harness succeeds only when those phases and cleanup evidence match. Inspect the lifecycle record.
Across the application and tutorial examples, 47 cases passed. The same 47 passed with warnings treated as errors and with collected node IDs reversed. To reproduce collection, all runs, diagnostic commands, and lifecycle checks without overwriting the supplied record, use tools/verify_all.py:
Command (writes a separate local-run report directory):
python tools/verify_all.py
The captured record is in evidence/captured-2026-11-29/; a new run defaults to evidence/local-run/. Reversed order is one deterministic order check, not a randomized-order or parallel guarantee. The manifest verifier checks file integrity without executing tests.
Optional exercise: Change the quantity IDs to more descriptive labels, run the six-case collection command again, and confirm that only identifiers change, not case count or assertions. Keep your exercise run separate from the supplied evidence.
Debug Fixture Failures and Prepare for Parallel Runs
Inspect discovery, dependencies, and setup
Use a specific test file to keep the output readable:
When investigating contamination, compare a failing test alone with the same test in its larger suite. Record the test node ID, resource variant, dependency trace, and setup/call/teardown phase before changing scopes.
Diagnose common fixture errors
S. No
Symptom
First checks
Corrective direction
1
Fixture not found
Name, test location, applicable conftest.py, required plugin
Fix discovery rather than importing unrelated test modules
2
ScopeMismatch
Consumer and dependency lifetimes
Narrow the consumer or redesign resource ownership
3
Fixture called directly
Calls such as db()
Request the fixture; extract an ordinary helper when needed
Fix initialization before diagnosing feature behavior
6
Teardown error
Cleanup traceback and resource ownership
Preserve the error; repair cleanup instead of suppressing it
Why is my fixture not found? pytest could not resolve the requested name in the test’s accessible fixture set. Check the spelling, directory visibility, applicable conftest.py, and any required plugin before changing imports or scope.
For shared external services, consider names containing a run identifier, worker identifier, and test-specific component. Do not let one worker’s cleanup delete another worker’s records. Resource names alone do not create isolation: verify permissions, ownership, and deletion boundaries too.
Prefer independent resources where practical. A genuinely shared one-time setup needs explicit cross-process coordination and recovery; changing the scope string is not enough. The versions-used matrix marks this parallel guidance as documentation-reviewed, not executed.
pytest Fixtures Design Checklist
S. No
Area
Checks before adoption
1
Dependencies
Can readers see what each test needs? Is setup order expressed by dependencies?
2
State
Is mutable state isolated? Is every broader scope justified by a real reuse need?
3
Cleanup
Does every acquired resource have an owner? Are assertion-failure and partial-setup cleanup verified?
4
Execution
Do assertions check behavior and recovery? Can tests run alone and in another order? For workers, are resource and deletion boundaries explicit?
Conclusion
Start with small, function-scoped pytest fixtures. Introduce broader scope, automatic activation, or factory patterns when they solve a specific problem, and keep the resulting dependencies visible. Well-designed pytest fixtures make every test’s prerequisites, lifetimes, and cleanup responsibilities explicit. Choose scope deliberately, keep mutable state isolated, verify teardown after failures, and confirm parallel behavior before relying on it. As a software testing company, Codoid applies these same patterns when building Python test suites for API and backend testing and long-running QA outsourcing engagements.
For framework selection, see Pytest BDD vs Behave: Pick the Best Python BDD Framework. As an optional application of fixture/resource ownership in mobile automation, see Appium Hybrid App Testing: WebViews, Permissions, and Context Switching. These related articles are not pytest API authorities. Run the complete fixture example: Open companion release v2, follow README.md, then run python tools/verify_all.py. Inspect your own environment, test outcomes, and cleanup evidence before adapting the pattern.
Struggling with flaky Python tests? Let our experts build reliable pytest fixtures
pytest fixtures supply the data, configuration, or resources a test needs, such as a database connection or a configured environment. A test requests a fixture by name, and pytest resolves its dependencies, provides its value, and manages its setup and cleanup.
What is the difference between a pytest fixture and a helper function?
Use a fixture when pytest should manage availability, dependencies, reuse, or cleanup. Use an ordinary helper for a calculation or transformation with no test lifecycle to manage. Never call a fixture directly as a function; request it as a test parameter instead.
What is the default scope of pytest fixtures?
The default scope is function, which means a new fixture instance is created for each test. You can also choose class, module, package, or session scope. Pick a broader scope only when you need to reuse something expensive, and keep mutable test data isolated per test.
Where should I put shared pytest fixtures?
Place shared fixtures in a conftest.py file. Tests in that directory and its subdirectories can use them without importing them. Moving a fixture into conftest.py changes where it is visible, not how long it lives; that still depends on its scope.
What is the difference between yield and return in pytest fixtures?
Use return when the fixture provides a value that needs no cleanup. Use yield when setup acquires a resource, such as a database connection, that must be released afterward. pytest runs the code after yield during teardown, even when the test assertion fails.
When should I use autouse fixtures?
Use autouse=True only for narrowly scoped prerequisites that every affected test needs. Avoid broad autouse fixtures in a top-level conftest.py, because they hide dependencies. Prefer an explicit fixture parameter when the dependency matters for understanding the test.
How can I see which fixtures a test uses?
Run python -m pytest --fixtures-per-test to see each test's fixture dependencies. Use --setup-plan to preview the fixture execution plan, or --setup-show to watch setup and teardown while the tests run.
Effective Playwright passkey testing involves testing registration, sign-in from an unauthenticated session, and reuse of the same passkey. Confirm that the server enrolls the credential and authenticates the intended account. A browser returning a credential is not sufficient evidence of successful authentication. Use Playwright’s built-in credentials API for repeatable application-flow tests and a separate Chromium CDP suite for additional authenticator controls. This guide pins Playwright 1.65.0. The credentials API arrived in 1.61, credential storage-state support in 1.62, and explicit counter preservation in 1.64.
Before you start: You need an authorized, non-production WebAuthn application, disposable accounts, and protected setup/read-only inspection hooks. The examples use TypeScript, Node.js 22.x, same-origin cookie sessions, explicit button-triggered ceremonies, and no attestation-verification requirement. Set PASSKEY_BASE_URL, PASSKEY_RP_ID, and the secret PASSKEY_TEST_API_TOKEN. These are illustrative application contracts, not standard WebAuthn routes. The files were syntax-checked, not dependency-type-checked or executed against an application. This guide focuses on building a robust Playwright passkey testing framework.
1. Choose the Right Approach for Playwright Passkey Testing
Built-In Credentials API for Application-Flow Testing
browserContext.credentials supplies cross-browser WebAuthn emulation. Install it before application code accesses WebAuthn. It intercepts the page’s credential methods; it does not exercise every browser’s native authenticator stack.
The pinned implementation generates ES256 responses: ECDSA using the P-256 curve and SHA-256. It reports successful user presence (UP) and user verification (UV) and uses attestation format none. These are emulator behaviors, not proof of biometric interaction, authenticator-policy enforcement, or attestation validation.
Chromium CDP for Authenticator Controls
Chrome DevTools Protocol (CDP) provides controls for virtual authenticators. Playwright’s CDP sessions are Chromium-specific, and CDP’s WebAuthn domain is experimental. Confirm command compatibility with the pinned browser.
Approach: Built-in credentials API | Use it for: Registration, sign-in, account binding, and imported-credential reuse | Do not treat it as: Native authenticator or hardware coverage
Approach: Chromium CDP | Use it for: Browser-integrated ceremonies and controlled verification/presence failures | Do not treat it as: Firefox, WebKit, or physical-device validation
Approach: Real devices and providers | Use it for: Native prompts, account selection, biometrics, synchronization, and recovery | Do not treat it as: A substitute for deterministic backend regression tests
Keep the built-in and CDP suites separate. An installed interceptor can answer the page request before the native path that the CDP test intends to exercise.
What Still Requires Real-Device Testing
Maintain real-device tests for Face ID, Touch ID, Windows Hello, security keys, cross-device sign-in, and provider synchronization. Software authenticators cannot establish that those interactions occurred. Browser autofill and account-chooser interaction are also different from returning a credential to JavaScript.
2. Define the WebAuthn Test Contract for Playwright Passkey Testing
Separate Authenticator Credentials, Server Records, and Login Sessions
When planning Playwright passkey testing, use three independently managed states:
State: Virtual authenticator | Evidence to inspect: Credential ID, RP ID, user handle, key material, counter | What it does not prove: Server enrollment
State: Server enrollment | Evidence to inspect: Credential-to-account association and verification data | What it does not prove: An authenticated browser session
State: Application session | Evidence to inspect: Cookies and the authenticated identity | What it does not prove: That this test used a passkey
Registration persists server-side verification data. Authentication uses that enrollment to verify an assertion. Restoring a signed-in session skips the sign-in journey rather than testing it.
Agree on RP ID, Origin, Account Binding, and Verification Policy
The relying party (RP) is the application using WebAuthn. Configure the allowed origin separately from the RP ID: the origin includes scheme and any nondefault port; the RP ID does not. Use valid HTTPS, or an appropriate localhost development origin.
For this contract, encode credential IDs, challenges, and userHandle as canonical, unpadded base64url. Keep account.id, your internal application identifier, separate from the encoded WebAuthn user handle. The handle must represent 1 to 64 opaque bytes and must not contain an email address or other personally identifying data.
The application converts JSON strings to browser buffers before navigator.credentials.create() or get() and serializes the returned credential before posting it to verification. Make the adapter responsible for this conversion; do not compare raw bytes, padded base64, and base64url as interchangeable strings.
The examples require residentKey: ‘required’, userVerification: ‘required’, and ES256. These are selected test prerequisites, not universal product defaults. Hosted identity providers, cross-origin frames, and redirect-based login need a separate origin/session/endpoint contract; do not broaden this example’s accepted origins merely to make such flows pass.
Identify Application-Specific Setup and Evidence
Implement or adapt the following interfaces. Options endpoints return options JSON directly; verification requests post the serialized credential directly, with its id at the top level.
Illustrative interface: PUT /__test/accounts/{lease} | Required contract: Protected provisioning; 200/201 with id, email, userHandle, and a single-use same-origin bootstrapPath
Illustrative interface: GET /__test/accounts/{lease}/credentials | Required contract: Protected, sanitized array of { id, userId, userHandle, counter }; no private keys
Illustrative interface: DELETE /__test/accounts/{lease} | Required contract: Idempotent removal of the account, enrollments, sessions, and challenges; 204/404
Illustrative interface: GET /api/me | Required contract: 401 without a session; otherwise 200 with { userId }; no redirect
Illustrative interface: POST /api/webauthn/register/options and /verify | Required contract: Real registration options and verification; accepted verification is 200 with { verified: true }
Illustrative interface: POST /api/webauthn/authenticate/options and /verify | Required contract: Real authentication; success as above; the CDP failure case expects 400 with { verified: false }
UI contract: /settings/passkeys provides the button “Create a passkey”; /login provides the label “Email” and buttons “Sign in with a passkey” and “Sign in without a username.” Authenticated pages provide “Sign out.” Add these stable completion/error targets:
Test ID: signed-in-email | Expected visible state: Exact test-account email after bootstrap and successful sign-in
Test ID: passkey-status | Expected visible state: Passkey added after accepted enrollment
Test ID: login-form | Expected visible state: Visible after sign-out completes
Test ID: passkey-error | Expected visible state: “Passkey sign-in failed. Try again.” after rejected authentication; the sign-in button is visible and enabled
These strings and status codes belong to the example application, not the WebAuthn standard. Adapt them together with the code.
Never expose authentication-bypass setup hooks in production. Restrict them to an isolated test deployment and disposable accounts; authenticate administrative calls with a runner-held secret. The bootstrap creates an enrollment session only. Happy-path WebAuthn verification remains real and unmocked.
3. Build an Isolated Playwright Passkey Fixture
Pin Dependencies and Install the Emulator Before Application Code Runs
Use a supported, patched Node.js 22.x runtime. For a new CommonJS sample project, initialize and install the dependencies below. Existing projects should retain their own compatible module settings. Commit the generated package manifest and lockfile.
This configuration uses NodeNext resolution with a CommonJS package. For an ESM repository, align the package type, imports, and compiler settings instead of copying this module setup unchanged. Playwright transforms TypeScript but does not perform semantic type checking; run npx tsc -p tsconfig.json –noEmit separately.
The 45-second test limit and 10-second waits are harness limits, not passkey performance targets. Raw recordings are disabled until an appropriate restricted-artifact policy is in place.
Allocate Disposable Accounts and Clean Up Test State
One account lease per test attempt prevents enrollment and session state leaking between tests. The provisioning hook must support idempotent cleanup by lease even when provisioning succeeds but its response is lost. Add server-side expiry for accounts abandoned by interrupted runners.
import { randomUUID } from 'node:crypto';
import { test as base, expect } from '@playwright/test';
export { expect };
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Set ${name}`);
return value;
}
export const rpId = required('PASSKEY_RP_ID');
export const adminHeaders = {
'X-Test-Token': required('PASSKEY_TEST_API_TOKEN'),
};
export type Account = {
id: string; email: string; userHandle: string;
bootstrapPath: string; testPath: string;
};
export function assertBase64Url(
value: unknown, field: string, maxBytes = Infinity,
): asserts value is string {
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value)) {
throw new Error(`${field}: expected nonempty unpadded base64url`);
}
const bytes = Buffer.from(value, 'base64url');
if (bytes.toString('base64url') !== value || bytes.length > maxBytes) {
throw new Error(`${field}: noncanonical encoding or invalid length`);
}
}
// This base fixture does not install WebAuthn interception.
export const appTest = base.extend<{ account: Account }>({
account: async ({ request, baseURL }, use) => {
if (!baseURL) throw new Error('Missing baseURL');
const testPath = `/test/accounts/${randomUUID()}`;
const errors: Error[] = [];
let phase = 'setup: account provisioning';
try {
const response = await request.put(testPath, {
headers: adminHeaders, maxRedirects: 0, timeout: 10_000,
});
phase = `setup: provisioning HTTP ${response.status()}`;
expect([200, 201]).toContain(response.status());
phase = 'setup: account contract';
const account = await response.json() as Account;
if (!account || ['id', 'email', 'userHandle', 'bootstrapPath']
.some(key => typeof account[key as keyof Account] !== 'string' ||
!account[key as keyof Account]) {
throw new Error('Invalid account contract');
}
assertBase64Url(account.userHandle, 'userHandle', 64);
const bootstrap = new URL(account.bootstrapPath, baseURL);
if (bootstrap.origin !== new URL(baseURL).origin ||
!account.bootstrapPath.startsWith('/')) {
throw new Error('Bootstrap must stay on the test origin');
}
phase = 'fixture use';
await use({ ...account, testPath });
} catch {
// Do not print bodies, bootstrap tokens, or request headers.
errors.push(new Error(`${phase} failed; raw details withheld`));
} finally {
let status = 'unavailable';
try {
const response = await request.delete(testPath, {
headers: adminHeaders, maxRedirects: 0, timeout: 10_000,
});
status = String(response.status());
expect([204, 404]).toContain(response.status());
} catch {
errors.push(new Error(`cleanup: deletion failed (HTTP ${status})`));
}
}
if (errors.length) throw new AggregateError(errors, 'Account fixture');
},
});
export const test = appTest.extend({
context: async ({ context }, use) => {
await context.credentials.install();
await use(context);
},
});
The context override installs interception before the dependent page fixture is used. The account fixture aggregates sanitized setup/use and cleanup failures, including available HTTP status, instead of letting a failed deletion overwrite a setup failure. Raw request bodies and bootstrap secrets stay out of those errors. Test assertions remain reported by Playwright; account expiry is still required when a runner cannot complete teardown.
For broader ownership and parallel-run design in your Playwright passkey testing, see Codoid’s Playwright Test Architecture guide.
4. Automate WebAuthn Passkey Registration in Playwright Passkey Testing
Trigger Registration and Wait for Server Verification
In a robust Playwright passkey testing suite, start from the disposable account’s enrollment session and verify its identity. Register response waiters before clicking; then require accepted verification and a visible completion state. The shared helper file also contains the sign-in and sign-out steps used below.
import type { Page, APIRequestContext } from '@playwright/test';
import {
expect, rpId, adminHeaders, assertBase64Url, type Account,
} from './passkey.fixture';
export function nextPost(page: Page, path: string) {
const origin = new URL(page.url()).origin;
return page.waitForResponse(response =>
new URL(response.url()).origin === origin &&
new URL(response.url()).pathname === path &&
response.request().method() === 'POST', { timeout: 10_000 });
}
export async function assertIdentity(page: Page, account: Account) {
const me = await page.request.get('/api/me', { maxRedirects: 0 });
expect(me.status()).toBe(200);
expect(await me.json()).toMatchObject({ userId: account.id });
await expect(page.getByTestId('signed-in-email')).toBeVisible();
await expect(page.getByTestId('signed-in-email')).toHaveText(account.email);
}
export async function signOut(page: Page) {
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
await expect(page.getByTestId('login-form')).toBeVisible();
await expect.poll(async () =>
(await page.request.get('/api/me', { maxRedirects: 0 })).status(),
).toBe(401);
}
The pubKeyCredParams assertion checks that the application offers { type: ‘public-key’, alg: -7 }, matching the ES256 prerequisite. The emulator is not a full algorithm-negotiation test: verify unsupported algorithms in a non-intercepted browser/CDP or backend verifier test.
Inspect the Created Credential and Confirm Account Association
The lifecycle test connects the submitted credential ID to the emulator record and the sanitized server record. The expected user handle and account ID must agree with the test contract; a success toast alone cannot establish that association. The exact-one-record assertion is appropriate only because this fixture provisions an empty account.
Do not compare public keys using unrelated encodings. Playwright exports SPKI (SubjectPublicKeyInfo) public-key data; server libraries may store a different representation. Normalize formats deliberately or test through the verifier rather than assuming two encoded strings should match.
Test Duplicate-Registration Protection
For an excluded-credential test, retain the existing credential, require its ID in excludeCredentials, and attempt enrollment again. Assert a recoverable UI result and an unchanged server credential count. Separately, when the product permits another passkey, enroll a distinct credential and verify both belong to the intended account. Excluded-credential protection does not mean an account may have only one passkey.
5. Automate Passkey Sign-In in Playwright Passkey Testing
Start Unauthenticated and Authenticate with the Registered Credential
Every sign-in below in your Playwright passkey testing suite requires /api/me to return 401 before the ceremony, then checks accepted verification, the expected account ID, and the displayed email. The browser-bound request client shares the context’s cookies. Token-based applications must adapt the identity check to their actual token path.
Important: The imported-credential cases below prove reuse, not the original credential’s discoverability. Playwright makes seeded credentials discoverable. The first test verifies original discovery before any export or reseeding.
Cover Username-First and Discoverable-Credential Flows
The original-credential test registers once, keeps the same authenticator, signs out, confirms the unauthenticated state, and requires an empty credential allowlist. It then checks that the submitted credential authenticates the expected account. No credential export, storage snapshot, or recreation occurs in that test.
The two imported-credential cases instead create a new context for each sign-in and carry the latest credential state forward. Username-first sign-in requires the expected ID in the allowlist; username-free sign-in requires no listed credentials. The consecutive-challenge check detects accidental reuse in these attempts; it does not prove randomness or the server’s full replay policy.
Neither test validates conditional autofill or a native account picker. Conditional mediation involves a pending browser request and user selection; the interceptor also overrides capability checks. Keep native capability, selection, and fallback tests separately configured.
6. Reuse Passkey Credentials in Playwright Passkey Testing
Capture and Reseed a Registered Test Credential
Transfer the credential ID, user handle, matching key material, RP ID, and current counter together. Keep its server enrollment alive. A fresh random key with the same account label is not the registered passkey, and creating a virtual credential does not enroll it on the server.
This is test-fixture reuse, not provider synchronization. The local warning beside the test is important: imported credentials cannot demonstrate that the original registration produced a discoverable credential.
Save Virtual Credentials with Storage State
storageState({ credentials: true }) opts into saving virtual credentials, including their private keys and counters. Restoring a state containing them installs the virtual authenticator. Remove session-bearing state when the purpose is to test authentication, not bypass it.
Optional TypeScript fragment, not a sixth runnable test file:
// Fragment: sourceContext, browser, and baseURL come from your test.
const snapshot = await sourceContext.storageState({ credentials: true });
const fresh = await browser.newContext({
baseURL,
storageState: { ...snapshot, cookies: [], origins: [] },
});
try {
// Assert /api/me returns 401, then perform the normal sign-in flow.
// Keep the matching server enrollment alive throughout this test.
} finally {
await fresh.close();
}
Use this instead of explicit reseeding, not in addition to it. For cross-run reuse, provide a separate managed enrollment lifetime: the per-test fixture above intentionally deletes its account. Save only after in-flight ceremonies finish, and keep credential state in protected, ignored storage with short retention. Never publish a fixture containing working private keys.
Preserve Counters and Avoid Shared-Credential Races
When scaling Playwright passkey testing, a stale snapshot can explain why reuse works once and then fails. After authentication updates the server’s counter, restoring an older credential state can produce a non-increasing counter. Capture the current state rather than resetting the server to hide the failure.
The example’s +1 assertion assumes one emulator assertion per button-triggered attempt. It is not a universal authenticator rule: some authenticators legitimately report zero. Follow the verifier and product policy for those cases.
Assign separate credentials to parallel workers and browser projects. A sequential reuse test should own its entire lifecycle; cloning one mutable snapshot into concurrent tests creates avoidable counter races.
7. Use Chromium CDP for Advanced Playwright Passkey Testing
Configure a Virtual Authenticator and Observe Credential Events
This separate file imports appTest, which does not install the interceptor. It registers through the real UI, signs out, and requests an invalid signature. Credential events show authenticator activity; the verification response, identity endpoint, and recovery UI establish the application outcome.
Exercise Verification Failures, Missing Presence, and Invalid Responses
Use separate cases so each failure has an identifiable cause:
Control: setUserVerified(false) | Action: Attempt a ceremony requiring verification | Required evidence: Failure or deliberate cancellation within the limit; no new session; identify the rejection layer
Control: setAutomaticPresenceSimulation(false) | Action: Withhold simulated user presence | Required evidence: Pending ceremony can be deliberately aborted; the UI becomes usable again
Control: setResponseOverrideBits | Action: Produce an invalid signature or altered UP/UV flags | Required evidence: Rejection at the intended layer; no new authenticated identity
These are documented controls, not guarantees that every browser version follows the same observable sequence. Disabling automatic presence does not click Cancel. Exercise the application’s cancellation path, independently bound the test, and confirm recovery; a runner timeout alone is not a recovery test.
A browser can reject before sending verification. To prove server enforcement, use a backend case that reaches the verifier with a well-formed, targeted fixture rather than treating an absent request as evidence of server rejection.
8. Build a Regression Matrix for Playwright Passkey Testing
These are acceptance cases to add around the example suite for comprehensive Playwright passkey testing. Start negative authentication cases without a session and require no newly authenticated identity afterward. The tables specify design expectations, not executed results.
Missing, Deleted, Revoked, and Wrong-Account Credentials
Preconditions and action: Empty authenticator; attempt sign-in | Layer: Application flow | Expected outcome and evidence: Recoverable error; no accepted verification or session
Preconditions and action: Delete the virtual key but retain server enrollment | Layer: Application flow | Expected outcome and evidence: Deleted key cannot authenticate; server record remains
Preconditions and action: Revoke enrollment but retain the key | Layer: Browser + backend | Expected outcome and evidence: Server refuses the credential; no new session; revocation evidence
Preconditions and action: Submit account A’s credential in B’s username-first ceremony | Layer: Backend + browser | Expected outcome and evidence: No account substitution; intended rejection and no B session
Preconditions and action: Enroll A and B; run separate username-free cases with only A’s or B’s credential available | Layer: Application flow | Expected outcome and evidence: A’s ID/handle resolves to A; B’s resolves to B; an empty allowlist and correct displayed identity each time
Preconditions and action: Enroll a second, distinct passkey for A using another authenticator | Layer: Application + backend | Expected outcome and evidence: Two distinct IDs mapped to A; each authenticates A independently
For the two-account case, controlled credential availability tests identity mapping, not native picker interaction. A real chooser test must present both eligible credentials and select each intended account in a supported device/browser environment. The pinned interceptor chooses a matching credential programmatically; do not mistake that for a chooser.
Deleting a virtual credential and revoking enrollment are different operations. Define separately whether revocation also invalidates sessions created earlier. For the two-passkey case, adapt the exact-one-record helper to compare the intended two-record set.
Expired Challenges, Replay, Invalid Origin, and RP Mismatch
Preconditions and action: Move a server test clock across the configured challenge expiry | Layer: Backend | Expected outcome and evidence: Accept before expiry; reject at/after the product’s documented boundary
Preconditions and action: Resubmit an accepted assertion; then race two submissions of one challenge | Layer: Backend | Expected outcome and evidence: No replay acceptance; at most one concurrent acceptance; challenge-consumption evidence
Preconditions and action: Send a validly constructed assertion from an unapproved origin | Layer: Backend | Expected outcome and evidence: Origin rejection rather than an unrelated parsing failure
Preconditions and action: Request a disallowed RP ID without the interceptor | Layer: Native browser/CDP | Expected outcome and evidence: Browser rejection; no accepted authentication
Preconditions and action: Verify an assertion for a different RP ID | Layer: Backend | Expected outcome and evidence: RP-ID-hash rejection; no new session
Use your verifier’s test utilities for targeted fixtures. Editing clientDataJSON without rebuilding the signed fixture can also break the signature, making the failure ambiguous. Require a sanitized internal verification reason while keeping public authentication errors appropriately generic.
Network Failures, Retries, and Concurrent Attempts
Preconditions and action: Fail options retrieval before credential creation/use | Layer: Browser + network fault | Expected outcome and evidence: Clear error, enabled retry, no session
Preconditions and action: Lose the verification response after possible server acceptance | Layer: Integration | Expected outcome and evidence: Reconcile actual identity/session state; do not blindly replay the assertion
Preconditions and action: Double-click or start competing ceremonies | Layer: Browser + backend | Expected outcome and evidence: Documented concurrency behavior; no account mix-up or duplicate acceptance
Preconditions and action: Fail enrollment verification after local key creation | Layer: Integration | Expected outcome and evidence: No false enrollment success; explicit orphaned-key and retry handling
Preconditions and action: Use an unsupported capability or controlled passkey failure | Layer: Separately configured UI/native case | Expected outcome and evidence: Approved fallback becomes available; no session before fallback; intended identity and success UI only after fallback succeeds
For unsupported-capability UI testing, omit the built-in interceptor and stub only the application’s capability boundary. Label this a UI-contract test, not device validation. Confirm actual unsupported-device behavior separately. Do not invent a password or recovery fallback that the product does not support.
Distinguish a request that never reached the server from an accepted request whose response was lost. Check the resulting session before choosing recovery; when another authentication is needed, begin a new ceremony with a new challenge.
9. Run Playwright Passkey Testing in CI and Diagnose Failures
Isolate Workers, Retries, and Browser Projects
To run Playwright passkey testing reliably, the configuration explicitly uses headless mode. These virtual-authenticator tests are intended for CI; they still require working application endpoints, browser dependencies, and compatible pinned binaries. Headless execution does not add native-device coverage.
After initial installation has generated a lockfile, use this sequence on the authorized deployment:
# Requires a generated and committed package-lock.json.
npm ci
npx tsc -p tsconfig.json --noEmit
npx playwright install --with-deps chromium firefox webkit
npx playwright test --project=chromium --project=firefox --project=webkit
npx playwright test --project=chromium-cdp
The TypeScript check includes all five named files. Record the resolved package versions, browser revisions, application build, expected origin/RP ID, sanitized outcomes, and cleanup status. Give retries fresh leases unless one test deliberately owns the sequential recovery scenario. Separate account ownership matters when tests modify server state.
Collect Evidence Without Exposing Credentials
Record the test ID, browser project, flow, sanitized verification decision, account alias, observed counter transition, and cleanup result. Restrict artifacts containing credential IDs and user handles as well as clearly secret values.
Credential exports contain private keys; saved authentication state can contain impersonation-capable cookies. Keep both out of Git and ordinary logs. Do not pass complete private-key-bearing objects into assertions that might print them. Recordings can also expose bootstrap tokens and protected API requests; enabling them requires access controls, redaction where possible, and defined retention.
Troubleshoot Enrollment, Sign-In, and Reuse Failures
Symptom: Native prompt appears in the application-flow suite | Check next: Fixture import and installation order
Symptom: Sign-in passes without a verification request | Check next: Restored session state; missing pre-sign-in 401 assertion
Symptom: Reuse works once, then fails | Check next: Stale counter snapshot or concurrent owners
Error names are diagnostic clues, not a one-to-one cause map. The browser and emulator may differ, and an exception alone does not prove that a server request occurred. Use the layer-specific evidence alongside the error.
CONCLUSION
Release-readiness takeaway: Require accepted enrollment, original-discoverability evidence where needed, a genuinely unauthenticated starting state, the correct authenticated identity, visible completion/recovery, and repeatable reuse. Place each negative test at the layer that can demonstrate the intended rejection. Treat native-device behavior as a separate release obligation. A complete Playwright passkey testing strategy covers all these boundaries.
Can Playwright test passkeys in Firefox and WebKit?
Yes, through the built-in credentials API's cross-browser emulation. This does not establish coverage of those platforms' native authenticator stacks. The CDP example remains Chromium-specific.
Does Playwright storage state save passkeys?
It can include virtual credentials when credentials: true is requested. It does not export passkeys from an operating system or a real password manager. Remove session-bearing state when testing sign-in.
Does adding a virtual credential register it with the application?
No. It populates the emulator. The server must already hold the matching enrollment, created through registration or an explicitly provisioned test fixture.
Can virtual-authenticator tests validate Face ID or Touch ID?
No. They validate application behavior around simulated credential operations, not actual biometric interaction. Keep biometric acceptance in the real-device plan.
Playwright HAR replay lets a browser test fulfill matching HTTP requests from a saved HTTP Archive instead of requiring the same live API to respond on every run. The practical pattern is to record traffic from a controlled test environment, scope the HAR to the endpoints the UI scenario needs, and install routeFromHAR() before the application sends those requests. For requests that enter the HAR route but do not match an entry, Playwright can abort or fall back according to the configured notFound policy (Playwright HAR mocking guide). This guide is based on @playwright/test 1.63.0, the npm latest stable release verified on October 7, 2026.
Critical scope rule: A url filter and notFound solve different problems. The url option decides which requests enter the HAR route. notFound decides what happens when an in-scope request has no matching HAR entry. Requests outside the HAR url filter are not made hermetic by notFound: 'abort'.
Playwright HAR replay is most useful when the purpose of the test is to validate browser behavior under a known HTTP response state. It does not rerun server business logic, database work, queues, downstream services, or recorded network timing. Keep direct API, contract, integration, and selected live end-to-end coverage for those risks. Codoid’s QA automation services combine all these layers in a single strategy.
HAR replay is match-driven. Playwright matches recorded exchanges by URL and HTTP method, and POST requests also require matching POST data.
A scoped routeFromHAR() does not control traffic outside its URL pattern. Model full network isolation separately when you need it.
Use notFound: 'abort' to expose missing in-scope HAR entries. Use fallback only when another route or the network is intentionally allowed.
Use focused HAR fixtures for coordinated UI states, hand-written routes for volatile or synthetic edge cases, and real API and end-to-end coverage for integration confidence.
HAR replay does not reproduce recorded latency and does not put the browser offline. Those are separate test dimensions.
What Playwright HAR Replay Testing Actually Does
A HAR file captures a collection of HTTP request and response exchanges from a browser journey. It can include request and response headers, cookies, content, timings, and other metadata. Playwright can route browser requests against that collection and fulfill a request when the current request matches a recorded entry. This is request matching, not a general guarantee that responses are consumed in the temporal order in which they were originally recorded (Playwright Mock APIs).
That distinction matters when the same endpoint is called repeatedly. If multiple recordings match, Playwright selects the entry with the greatest number of matching headers. Do not depend on recorded order to distinguish otherwise indistinguishable requests. Instead, make the request state distinguishable, split scenarios into separate fixtures, or use a focused hand-written mock.
What HAR Replay Can and Cannot Reproduce
S. No
Test concern
HAR replay fit
Use instead or alongside when needed
1
Recorded HTTP status, headers, and response body
Strong fit when the request matches a HAR entry
route.fulfill() for a smaller synthetic response
2
Coordinated multi-request UI data state
Strong fit
Direct API setup if the test must create real backend state
3
Redirects
Supported for matching recorded redirects
Live coverage if redirect behavior depends on current server policy
4
Different POST inputs
Only when POST data matches a recording
Separate fixtures or route.fulfill() for broad input variation
5
Offline behavior
HAR replay does not put the browser context offline
use.offline or browserContext.setOffline(true)
6
Slow or variable latency
Recorded HAR timing is not replayed as network delay
Dedicated network conditioning or application-specific delay injection
7
Server logic, databases, queues, downstream services
Not reproduced
API, contract, integration, and live end-to-end tests
When Playwright records a minimal HAR for routing, it intentionally omits timing, page, cookie, security, size, and other HAR fields that are not used for replay. That is why a response that was slow during capture does not automatically replay slowly (BrowserContext.routeFromHAR()).
How Playwright Matches Requests to HAR Entries
Playwright matches the request URL and HTTP method strictly. For POST requests, it also matches the POST payload strictly. If several entries qualify, the recording with the most matching headers is chosen. Matching redirects are followed automatically.
S. No
Request change
Likely outcome
Testing implication
1
GET /api/orders?page=1 becomes page=2
The URL differs, so the original entry may not match
Record the intended variant or mock that volatile request separately
2
POST quantity changes from 1 to 2
POST data no longer matches strictly
Use separate scenario data or a focused route
3
Generated timestamp or UUID changes
Payload or query may miss the fixture
Stabilize test data or isolate the volatile endpoint
4
Several entries have the same URL, method, and body
Headers may disambiguate. Recorded order is not the documented selector
Do not rely on temporal sequence playback
5
A new endpoint is introduced
If inside HAR scope, notFound applies. If outside scope, HAR does not control it
Decide deliberately whether that dependency belongs in the fixture
How to Record a HAR File in Playwright
Prerequisite for Relative URLs: Configure baseURL
The examples below use relative navigation such as page.goto('/orders'). That requires Playwright Test to have use.baseURL configured. If your project does not configure baseURL, use an absolute URL in page.goto() (Playwright baseURL guidance).
Record a Focused Fixture With routeFromHAR({ update: true })
For a test-specific fixture, use update: true while authoring or deliberately refreshing the HAR. In update mode, Playwright records actual network information instead of serving from the existing HAR and writes the file when the browser context closes. Limit the recording to the endpoints the scenario needs whenever possible.
Authoring safeguard: Do not leave update: true enabled in the normal replay path. With update enabled, the test is recording current network information rather than proving that the saved fixture can replay the scenario.
Record HAR Quickly From the Playwright CLI
The CLI is useful for exploratory capture. Open the browser, exercise the flow, and save only API requests. Playwright documents --save-har and --save-har-glob for this workflow.
npx playwright open \
--save-har=orders.har.zip \
--save-har-glob="**api/**" \
https://example.com
For repeatable suite maintenance, prefer a test-controlled recording path such as routeFromHAR({ update: true }) so the same setup, credentials, and navigation can be reviewed in code. Use CLI capture when you are discovering the required traffic or creating an initial fixture interactively.
Other Recording Options: recordHar and tracing.startHar()
browser.newContext({ recordHar: ... }) records network traffic for the entire context until it closes. Its mode defaults to full. Content defaults to attach for .zip output and embed for other file extensions. Await browserContext.close() so the HAR is saved.
Playwright also provides tracing.startHar() and tracing.stopHar(), added in v1.60. This can be useful when HAR capture needs to be started and stopped explicitly within the lifecycle of an existing context.
Choosing Minimal vs Full and Embed vs Attach
S. No
Option
Best fit
Important behavior
1
minimal
Replay-oriented fixtures
Keeps information required for HAR routing and omits replay-unused metadata
2
full
Inspection or external HAR tooling needs fuller metadata
Default for recordHar and tracing.startHar()
3
embed
Keep response bodies inside HAR JSON
Convenient single HAR, potentially bulky
4
attach
Keep response bodies as attached resources or ZIP entries
Convenient for .har.zip fixture packaging
How to Replay a HAR with routeFromHAR()
page.routeFromHAR() vs browserContext.routeFromHAR()
S. No
Use case
Prefer
1
One page owns the scenario and all relevant traffic
page.routeFromHAR()
2
Popups, multiple pages, or shared browser-context traffic must use the same fixture
browserContext.routeFromHAR()
Install the HAR route before the first request you expect it to handle.
Replay a Known API State
import { test, expect } from '@playwright/test';
test('shows the recorded orders state', async ({ page }) => {
await page.routeFromHAR('tests/hars/orders-success.har.zip', {
url: '**/api/**',
notFound: 'abort',
});
await page.goto('/orders');
await expect(page.getByText('ORD-1042')).toBeVisible();
await expect(page.getByText('Ready to ship')).toBeVisible();
});
The order ID and UI copy above are illustrative. Replace them with controlled test data from your application.
URL Scope vs notFound: The Critical Difference
Rule:url decides whether a request is handled by the HAR route. notFound decides what happens when an in-scope request has no matching HAR entry.
S. No
Request
With url: **/api/**
Effect of notFound: abort
1
/api/orders
Inside HAR scope
If no HAR entry matches, the request is aborted
2
/api/recommendations
Inside HAR scope
If unrecorded, the request is aborted
3
/analytics/events
Outside HAR scope
The HAR route does not serve or abort it. Another route or the network may handle it
4
/assets/app.css
Outside HAR scope
The HAR route does not control it
If you need a fully isolated browser-network test, design that isolation explicitly. For example, keep the HAR focused on application APIs and add separate allow-list or blocking routes for third-party analytics, telemetry, or other out-of-scope traffic. Do not assume a narrow HAR url filter plus notFound: 'abort' blocks every browser request.
Abort vs Fallback
Use abort when an unexpected missing HAR entry inside the route scope should fail the test. Use fallback when the missing in-scope request is intentionally allowed to continue. At browser-context level, fallback continues to the next route handler. If nothing else handles the request, it can ultimately reach the network. At page level, Playwright documents fallback as sending missing requests to the network.
S. No
Policy
Use it when
Primary risk
1
abort
You want in-scope fixture misses to fail visibly
Legitimate API changes require deliberate fixture updates
2
fallback
A hybrid scenario intentionally permits another route handler or live request
Unreviewed live dependencies can reduce isolation
Request-to-HAR Decision Flow
Does the request URL match routeFromHAR({ url: ... })?
↓
Yes → Does a HAR entry match URL + method
(plus POST data when applicable)?
↓
Yes → Fulfill from the HAR
No → Apply notFound: abort or fallback
No → The HAR route does not handle it.
Another route or the network may.
Service Workers, WebSockets, Offline Mode, and Other Boundaries
Service Workers
Playwright does not serve requests intercepted by a Service Worker from HAR and recommends blocking Service Workers for request-interception tests when necessary. However, blocking a worker can change application behavior, so keep worker-enabled coverage when caching, offline behavior, or worker routing is itself under test. Playwright documents Service Worker support as Chromium-based.
HAR replay is an HTTP and HTTPS request-response fixture mechanism. If the application uses WebSockets, use page.routeWebSocket() or browserContext.routeWebSocket() for WebSocket message mocking or interception, or keep live integration coverage for the socket behavior.
Offline and Latency Are Separate Test Dimensions
HAR replay does not make the browser offline. Use the offline context option or browserContext.setOffline(true) when the scenario requires no network. Likewise, do not treat recorded HAR timing as latency replay. Minimal HAR routing omits timing because it is not used to fulfill requests.
How to Maintain HAR Fixtures Safely in Git and CI
Playwright’s guide describes committing HAR fixtures alongside tests. That can make CI repeatable, but HAR data can contain headers, cookies, response bodies, and other captured information. Treat every HAR as reviewable test data rather than assuming it is safe to commit.
Record from a controlled test environment, not from a production session containing real customer data.
Use synthetic accounts and stable test data where possible.
Filter capture to the endpoints required by the scenario.
Inspect authorization headers, cookies, query parameters, request bodies, and responses before committing or refreshing a fixture.
Use scenario-specific names such as checkout-success.har.zip and checkout-auth-expired.har.zip.
Refresh a fixture because intended application or API behavior changed, not merely because the test failed.
Review HAR changes in code review and rotate any secret that was accidentally committed. Editing the current file does not remove it from repository history.
A Practical Test-Suite Strategy
The strongest automation strategy uses Playwright HAR replay alongside other layers, not as a replacement for them.
Use direct API or contract tests for current service behavior, authorization, business rules, and response contracts.
Use HAR-backed browser tests for coordinated, high-value UI scenarios where live dependencies add setup cost or instability without being the subject of the test.
Use hand-written routes for small synthetic states or highly volatile requests that are clearer in code than in a HAR fixture.
Keep a smaller set of live browser end-to-end checks for integrations that genuinely need end-to-end proof.
When a live Playwright test fails, diagnose the original failure before replacing its dependency with a HAR. Mocking should isolate an intentional test boundary, not hide a product or environment defect.
HAR Replay vs route.fulfill() vs Live Backend Testing
S. No
Approach
Best for
Strength
Main limitation
1
HAR replay
Multi-request browser flows with recorded states
Reuses coordinated HTTP exchanges
Can become stale. Server logic is not executed
2
route.fulfill()
Small mocks and rare or synthetic edge states
Explicit and easy to review
Noisy if you model many endpoints
3
Direct API and contract tests
Service behavior, auth, business rules, contracts
Tests the current backend without UI noise
Does not validate browser rendering
4
Live browser end-to-end
Critical integrated journeys
Highest integration realism
More environment, data, and network dependencies
A useful ownership rule: mock at the browser boundary when the test question is “How does the UI behave under this known HTTP state?” Use real API and integration coverage when the question is “Can the backend actually produce and process this state now?”
Specify exactly which requests belong inside the HAR route scope
2
Configure baseURL
Set use.baseURL before copying examples that use relative page.goto() URLs, or use absolute navigation URLs
3
Record from a controlled environment
Use synthetic data and a narrow URL filter
4
Choose HAR format deliberately
Prefer minimal for replay-only fixtures. Choose .har or .har.zip with intent
5
Install route before requests
Call routeFromHAR() before the first matching request fires
6
Use abort for fixture misses
Fail visibly when unexpected in-scope entries are missing. Control out-of-scope traffic separately if full network isolation is required
7
Compare POST bodies and volatile fields
Match POST bodies, timestamps, UUIDs, and query parameters when a recording stops matching
8
Handle Service Workers correctly
Block Service Workers only when worker behavior is not itself part of the test objective
9
Use routeWebSocket for WebSockets
Do not use HAR replay for WebSocket message behavior
10
Review HAR fixtures before commit
Inspect for credentials, cookies, and sensitive payloads
11
Refresh fixtures only on intended change
Keep real API and integration coverage as an independent source of truth
Conclusion
Playwright HAR replay is most reliable when teams treat it as deliberate fixture design. Scope the HAR carefully, understand strict request matching, distinguish route scope from notFound behavior, and use fixture misses as diagnostic signals instead of reflexively refreshing the archive. That gives browser tests stable, reviewable HTTP states without pretending the recorded responses prove that the current backend still works. The strongest automation strategy combines Playwright HAR replay for coordinated UI states, route.fulfill() for focused synthetic conditions, direct API and contract testing for service behavior, and selected live end-to-end journeys for integration confidence.
If network-driven Playwright flakiness or unclear test boundaries are making CI difficult to trust, Codoid’s QA automation services include Playwright-based web automation and broader API automation capabilities.
Need Help Stabilizing Your Playwright Network Tests?
Use routeFromHAR() with update: true for a test-controlled fixture, browser.newContext({ recordHar: ... }) for context-wide capture, tracing.startHar() when you need explicit start and stop control, or the CLI --save-har option for quick interactive recording.
What is the difference between page.routeFromHAR() and browserContext.routeFromHAR()?
page.routeFromHAR() applies to requests made by that page. browserContext.routeFromHAR() applies across pages in the context, which is usually the better fit for popups or multi-page flows that share one fixture.
Why does my Playwright HAR POST request not match?
Playwright matches POST data strictly in addition to URL and HTTP method. Dynamic timestamps, generated IDs, signatures, or changed JSON fields can make the request miss the recorded entry.
What is the difference between notFound: abort and fallback?
abort fails an in-scope request when the HAR has no matching entry. At context scope, fallback continues to the next route handler and can eventually reach the network. At page scope, Playwright documents missing fallback requests as going to the network.
Does notFound: abort block requests outside the HAR URL filter?
No. Requests outside the routeFromHAR url filter are not handled by that HAR route, so notFound does not apply to them. Add separate route controls if full network isolation is required.
Can Playwright HAR replay simulate offline mode or slow latency?
No. HAR replay fulfills recorded HTTP exchanges. It does not put the context offline or replay recorded timing as latency. Use Playwright offline emulation for offline tests and a separate network-conditioning approach for latency and bandwidth scenarios.
Does HAR replay work with Service Workers?
Requests intercepted by a Service Worker are not served from HAR. You can block Service Workers for interception-focused tests, but keep separate worker-enabled coverage when worker behavior matters.
Does HAR replay mock WebSocket messages?
No. Use page.routeWebSocket() or browserContext.routeWebSocket() for WebSocket message mocking or interception.
Should Playwright HAR files be committed to Git?
They can be, and Playwright documents committing HAR fixtures with tests. First inspect them for secrets, cookies, sensitive data, and unnecessary traffic. Prefer controlled synthetic test data.
When should a HAR fixture be refreshed?
Refresh it when the intended API contract, request shape, or scenario data has changed. Do not automatically regenerate a failing fixture, because that can overwrite a useful regression signal.
Can HAR replay replace API or end-to-end testing?
No. HAR replay isolates selected browser behavior from live dependencies. Keep real API, contract, and integration tests for backend confidence, and a smaller set of live end-to-end checks for critical integrated journeys.
A Playwright test that fails once and passes immediately afterward is more dangerous than it looks. The retry may turn the pipeline green, but it does not explain whether the original failure came from a race condition, unstable test data, an API error, an overlay blocking a click, resource contention, or an actual application defect. The goal of debugging flaky Playwright tests is therefore not simply to make the next execution pass. It is to preserve enough evidence from the failing attempt to determine why the outcome changed.
Playwright provides several complementary debugging signals: traces, screenshots, browser and test logs, network activity, HTML reports, and retries. Used together, they can make intermittent failures reproducible and diagnosable. Used carelessly, particularly retries, they can also conceal instability. This guide uses the current Playwright 1.63-era feature set. Version 1.63 added the retain-on-failure-and-retries trace mode specifically to make comparison between failed and retried executions easier.
Codoid’s QA automation services help teams build reliable Playwright suites that surface instability early instead of hiding it behind retries.
To debug flaky Playwright tests without hiding failures, capture evidence from the original failure, compare it with the retry, and keep the initial failure visible to CI. Use Trace Viewer for execution history and DOM state, screenshots for visual checkpoints, network logs for API and transport failures, and only a small number of retries for additional diagnostic evidence.
For CI quality gates, Playwright’s failOnFlakyTests option is particularly important: a test that fails initially but succeeds on retry can still make the run fail instead of silently becoming a successful build.
Key Takeaways
Treat retries as diagnostic observations, not as a fix for flaky Playwright tests.
Use Trace Viewer as the primary CI debugging artifact because it combines actions, DOM snapshots, console output, errors, and network activity.
Keep screenshot: 'only-on-failure' for a lightweight visual record, and add named screenshots only around high-risk transitions when necessary.
Inspect both HTTP error responses and transport failures; a 500 response does not trigger Playwright’s requestfailed event.
Preserve both failed and retry traces when actively investigating intermittent failures.
Use failOnFlakyTests or --fail-on-flaky-tests when a pass-on-retry must not turn an unstable release gate green.
Before adding waits or more retries, check locators, auto-waiting, test isolation, shared state, network dependencies, and parallel execution.
What Is a Flaky Playwright Test?
A flaky Playwright test is a test whose outcome changes between executions even though the intended application behavior and test inputs have not deliberately changed.
Playwright Test formally categorizes a test as flaky when it fails on its first execution but passes on a retry. A test that passes initially is categorized as passed; one that exhausts its retries without passing is failed.
That distinction is useful, but not every intermittent failure is necessarily a bug in the test itself.
A flaky result may expose:
A race condition in the application
Unstable or eventually consistent backend data
Network or dependency failures
Shared test-account interference
Differences between CI and local environments
Brittle selectors
Missing asynchronous assertions
Resource pressure under parallel execution
A real product defect that occurs only under specific timing conditions
A consistently reproducible failure is different. If the same input fails every time for the same reason, it is a deterministic failure rather than a flake.
The debugging objective for flaky Playwright tests is to determine which variable changed between the failing and passing executions.
Why Flaky Playwright Tests Matter
flaky Playwright tests reduce the value of automation because developers stop being able to interpret a failing pipeline as a meaningful signal.
The common response, “rerun it,” creates a more serious problem. A defect may remain present while the second execution happens to avoid the conditions that exposed it.
Retries can make this especially misleading. When Playwright retries a failed test, it does not simply continue inside the same broken browser. Following a failure, Playwright shuts down the worker process and starts another worker with a new browser before performing the retry.
That reset is useful for isolation, but it also means:
A passing retry proves that the test passed in a fresh execution environment. It does not prove that the original failure was harmless.
For example, if the first run fails because two parallel tests modify the same customer account, the new worker may retry after the conflicting test has finished. The retry passes, but the underlying concurrency defect remains.
How Flaky Test Debugging Works
A useful debugging workflow correlates four types of evidence rather than relying on one artifact in isolation:
Trace: What actions occurred, what Playwright waited for, and what the DOM looked like around the failure?
Screenshot: What did the rendered page visibly look like at a specific moment?
Network evidence: Did the expected request happen, what HTTP status was returned, and did transport fail?
Retry comparison: Did the same action succeed after the worker and browser were reset?
The sequence is important.
A failed screenshot may show a spinner. The trace can reveal which action was waiting behind that spinner. The Network tab can reveal that /api/orders returned 503. A passing retry can then show the same endpoint returning 201.
That evidence points toward a very different root cause than simply increasing a locator timeout.
Step-by-Step: Configure Playwright to Preserve Evidence
1. Keep Retries Small and Make Flaky Tests Visible in CI
A practical starting configuration is:
// playwright.config.ts
import { defineConfig } from '@playwright/test';
const flakeDebug = process.env.FLAKE_DEBUG === '1';
export default defineConfig({
retries: process.env.CI ? 1 : 0,
// A fail-then-pass result still fails the CI run.
failOnFlakyTests: !!process.env.CI,
reporter: [
['html', { open: 'never' }],
['list'],
],
use: {
screenshot: 'only-on-failure',
trace: flakeDebug
? 'retain-on-failure-and-retries'
: 'on-first-retry',
},
});
Playwright recommends on-first-retry for routine CI tracing rather than recording every test because tracing every execution has a performance cost. Playwright 1.63 additionally provides retain-on-failure-and-retries, which keeps relevant executions so a failing attempt can be compared with its retry.
This gives two useful operating modes:
Normal CI: low-overhead trace collection on the first retry.
Flake investigation: preserve failed and retried executions for comparison.
The important setting is failOnFlakyTests. Without it, a failing attempt that later passes can leave the overall run successful. Playwright also exposes the equivalent --fail-on-flaky-tests command-line option.
2. Reproduce the Problem Before Modifying the Test
Avoid immediately adding another timeout or retry. First establish how frequently and under which execution conditions the problem appears.
For example:
FLAKE_DEBUG=1 npx playwright test tests/checkout.spec.ts --repeat-each=20
--repeat-each executes the selected test repeatedly and is useful for exposing intermittent timing problems.
Then compare the result with single-worker execution:
FLAKE_DEBUG=1 npx playwright test tests/checkout.spec.ts \
--repeat-each=20 \
--workers=1
Playwright supports --workers=1 specifically to disable parallel execution.
This comparison provides an immediate clue:
Flaky with normal parallelism but stable with one worker: investigate shared accounts, data, ports, databases, rate limits, or other shared resources.
Flaky in both modes: focus more strongly on application timing, network dependencies, selectors, assertions, or environment differences.
Twenty executions here are a diagnostic sample, not proof that the problem is permanently fixed if all twenty pass.
Trace Viewer provides considerably more context than a screenshot. It can show:
Actions and their duration
Before, action, and after DOM snapshots
The locator used
Playwright’s action log
The source line
Test errors
Browser and test console messages
Network requests and responses
Attachments
Browser and execution metadata
The timeline can also filter console and network information to the period surrounding a particular action.
Start at the failed action and work backward.
For a failed click, ask:
Did the locator resolve to the intended element?
Was the element stable?
Was it enabled?
Was another element intercepting pointer events?
Did navigation or rendering occur immediately before the failure?
Was the expected API response already delayed or failing?
Playwright automatically checks actionability conditions such as visibility, stability, event reception, and enabled state before actions such as locator.click(). A timeout can therefore mean more than “the element was not found.”
4. Use Screenshots as State Evidence, Not as Your Complete Debugger
Enable automatic failure screenshots:
use: {
screenshot: 'only-on-failure',
}
Playwright supports off, on, and only-on-failure screenshot modes, with artifacts normally stored in the configured test output directory.
A failure screenshot is useful for immediately spotting:
Cookie banners
Modal overlays
Validation messages
Logged-out sessions
Loading indicators
Wrong routes
Unexpected empty states
Layout differences
Its limitation is causality.
A screenshot tells you what the page looked like at one instant. It usually cannot tell you why it reached that state.
For a known flaky transition, attach a named checkpoint:
Playwright can attach files or buffers to tests and individual test steps, allowing the evidence to appear in supporting reports.
Do this selectively. Capturing screenshots after every action creates noise and artifact overhead while Trace Viewer already records a visual timeline when tracing is enabled.
5. Inspect Network Behavior Instead of Guessing About Backend Timing
A UI failure may actually be a network failure.
Trace Viewer’s Network tab displays requests made during the test and exposes information including method, status, duration, headers, request bodies, and response bodies. Network activity can also be filtered to the actions selected in the trace timeline.
For important transitions, make the backend dependency explicit:
Notice that waitForResponse() is registered before clicking the button. This prevents the test from missing a fast response that occurs immediately after the click. Playwright’s network documentation uses the same promise-before-action pattern.
You can also add targeted logging during an investigation:
The second listener matters because requestfailed does not mean “the server returned an error status.”
Playwright considers responses such as 404 and 503 successfully completed HTTP requests. requestfailed is emitted when the browser fails to obtain a response because of a transport-level problem such as a network error or timeout.
Without this distinction, an engineer may search for requestfailed events and incorrectly conclude that the network was healthy even though the application received a 500.
6. Compare the Failed Attempt with the Retry
The highest-value question is often not “why did this fail?” but:
What is different between the failed trace and the passing trace?
Compare:
S. No
Signal
Failed attempt
Passing retry
1
Locator
Same target?
Same target?
2
DOM
Overlay, stale state, missing data?
Expected state present?
3
Action duration
Near timeout?
Immediate?
4
API status
4xx or 5xx?
Expected 2xx?
5
Request timing
Slow or absent?
Normal?
6
Console
JavaScript error?
No error?
7
Authentication
Session expired?
Fresh session?
8
Test data
Conflicting record?
Available record?
9
Parallel activity
Competing test?
Conflict gone?
Playwright 1.63‘s retain-on-failure-and-retries mode is particularly useful here because it was designed to retain traces that allow failed and retry executions to be compared.
7. Fix the Synchronization or Isolation Problem, Not the Symptom
Suppose the trace shows:
const text = await page.locator('.status').textContent();
expect(text).toBe('Complete');
If .status changes asynchronously, this assertion observes one instant in time.
Playwright’s web-first assertions automatically retry until their condition succeeds or the assertion timeout expires. Playwright explicitly warns that non-retrying assertions against asynchronously changing pages can create flaky Playwright tests.
Likewise, avoid:
await page.waitForTimeout(3000);
followed by an assumption that three seconds must be enough.
Wait for the actual application condition instead:
That increases tolerance but provides no evidence that thirty seconds was actually the problem.
A better investigation follows the evidence.
Preconditions
The checkout test:
Creates a cart
Loads /checkout
Fills payment details
Clicks Place order
Expects a confirmation page
Evidence From the Failed Trace
Imagine the trace shows:
The button exists and is visible
A loading overlay appears above it
Playwright repeatedly reports that another element receives pointer events
/api/shipping/quote takes unusually long
The request eventually returns 503
The application does not remove the loading overlay
The screenshot merely shows a spinner.
The network evidence explains why it remained there.
The action log explains why Playwright correctly refused to click the button.
The passing retry then shows:
/api/shipping/quote returning 200
The overlay disappearing
The button becoming actionable
The click completing immediately
The root cause is therefore not “Playwright cannot click the button.” The test exposed an application and dependency path in which a failed shipping request leaves checkout blocked.
Increasing the click timeout would have hidden the useful symptom while leaving the underlying behavior unchanged.
Traces vs Screenshots vs Network Logs vs Retries
S. No
Debugging signal
Best question it answers
Main advantage
Main limitation
Recommended use
1
Trace
What sequence of events caused the failure?
Combines actions, DOM snapshots, logs, source, network data, and errors
More artifact and storage overhead
Primary CI debugging evidence
2
Screenshot
What did the user-visible page look like?
Fast visual diagnosis
No execution history or causality
Automatic on failure; targeted checkpoints when needed
3
Network logs
Did an API request fail, stall, or return unexpected data?
Reveals backend and transport problems
Does not explain every DOM or actionability problem
Inspect Trace Network tab and log critical endpoints
4
Retry
Does the behavior change in a fresh execution?
Supplies a second observation
Can hide failures if treated as success
Keep count low and report flakes explicitly
The tools answer different questions. A reliable debugging process correlates them rather than selecting one as a universal solution.
Best Practices for Debugging Flaky Playwright Tests
for quality gates where intermittent failures require investigation.
A retry can still collect useful evidence without allowing the build to appear stable.
Preserve the First Meaningful Failure
on-first-retry is efficient for general CI debugging, but when actively investigating a flake, preserving the failed execution itself is valuable.
On current Playwright versions, use:
trace: 'retain-on-failure-and-retries'
when comparing failed and retried attempts is worth the additional artifact cost.
Prefer State-Based Synchronization
Use locators, auto-waiting actions, web-first assertions, and explicit network expectations instead of arbitrary sleeps.
Playwright performs actionability checks automatically and provides retrying assertions specifically for asynchronous browser behavior.
Test Parallelism as a Diagnostic Variable
If a problem disappears with:
npx playwright test --workers=1
investigate shared server-side state rather than leaving the whole suite permanently serialized.
Playwright recommends isolated tests, and parallel workers should not depend on shared in-memory state. Teams that need help structuring this layer can benefit from reusable Playwright fixtures that isolate resources per worker.
Give Parallel Tests Independent Data
Separate test users, carts, organizations, records, and temporary resources where tests modify server-side state.
Playwright’s authentication guidance specifically recommends separate accounts per parallel worker for scenarios that modify shared server-side state.
Use Test Locks Only for Genuinely Shared Resources
Playwright 1.63 introduced named test locks. Tests sharing a lock do not execute concurrently, which can be useful for a truly exclusive external resource.
Common Mistakes When Debugging Flaky Playwright Tests
S. No
Mistake
Why it happens
Impact
Recommended fix
1
Increasing retries until CI becomes green
Retry appears cheaper than investigation
Instability becomes normalized
Keep retries limited and fail CI on flaky results where appropriate
2
Adding waitForTimeout()
Failure looks timing-related
Makes tests slower without proving readiness
Wait for observable UI or network state
3
Looking only at screenshots
Screenshot is easy to inspect
Root cause remains unknown
Correlate screenshot with trace and network activity
4
Treating every requestfailed absence as network success
Event name is misleading
HTTP 4xx and 5xx failures are missed
Inspect response statuses as well
5
Recording traces for every test
Maximum evidence seems safer
Increased runtime and storage indefinitely
Use targeted trace modes
6
Using force: true to bypass
Click is blocked intermittently
Can hide a real overlay or UI bug
Determine why the element cannot receive events
7
Sharing one mutable test account across workers
Setup is simpler
Cross-test interference
Use independent resources or deliberate locking
8
Raising global timeouts
Slow CI causes failures
Real performance and synchronization problems become harder to detect
Increase only the timeout that has a justified requirement
9
Assuming a passing retry proves the test is healthy
Final result is green
Initial failure is discarded
Treat pass-on-retry as a distinct flaky state
Troubleshooting Common Flake Patterns
Why does my Playwright test pass locally but fail in CI?
Start by comparing environment and execution conditions rather than increasing timeouts.
CI may have different CPU availability, browser versions, worker counts, network latency, authentication state, environment variables, or test data. Run the failing test repeatedly, preserve its trace, then compare normal parallel execution with --workers=1.
If the single-worker run is stable, shared state or resource contention becomes a stronger hypothesis. If both fail, inspect the trace for synchronization, network, and actionability differences.
Why is locator.click() timing out when the button is visible?
Visibility is only one of Playwright’s actionability checks.
For a normal click, Playwright also checks that the element is stable, receives pointer events, and is enabled. An overlay can therefore leave a button visibly present while preventing the click.
Open the failing trace and inspect its action log before using force: true.
Why does the retry pass when the first attempt failed?
The retry occurs after Playwright restarts the failed worker and its browser.
A fresh worker can remove several conditions that existed during the original run:
Stale browser state
Worker-scoped setup state
Timing overlap with another test
Temporary dependency failure
Shared-data conflict
Compare the first failure and retry rather than treating the retry as proof that the original error can be ignored.
Why do I see an HTTP 500 but no requestfailed event?
Because an HTTP 500 is still an HTTP response.
Playwright emits requestfailed when the browser cannot obtain an HTTP response, for example because of a network-level failure. Error statuses such as 404 and 503 still complete as HTTP requests.
The test may depend on a resource another worker can modify concurrently.
Common examples include:
One shared user account
A fixed database record
The same shopping cart
A global configuration setting
Rate-limited test credentials
Shared file paths
External systems that permit only one active operation
Use independent test resources where possible. If the resource is inherently exclusive, limit concurrency only around that resource rather than serializing unrelated tests.
Why does increasing the timeout make the flake disappear?
Because the test is being given more time, not necessarily because the synchronization problem has been fixed.
Inspect what consumed the additional time. If the application legitimately needs longer under a documented condition, a targeted timeout may be correct. If the timeout merely gives an uncertain race more opportunities to succeed, replace it with an observable readiness condition.
Playwright Tools for Flaky Test Investigation
Trace Viewer
Best for post-failure CI diagnosis.
npx playwright show-trace trace.zip
Trace Viewer exposes actions, DOM snapshots, logs, console events, network requests, errors, attachments, source locations, and execution metadata. Playwright recommends traces over standalone videos and screenshots for CI debugging.
The hosted Trace Viewer at trace.playwright.dev processes uploaded traces in the browser rather than transmitting their contents externally.
HTML Report
Use:
npx playwright show-report
The HTML report allows tests to be filtered by states including passed, failed, skipped, and flaky, then opened for detailed errors, steps, and attached artifacts. For a deeper walkthrough, see Codoid’s test reports guide.
UI Mode
Use:
npx playwright test --ui
UI Mode is useful while reproducing a problem locally and automatically provides tracing for interactive debugging.
Playwright Inspector
Use:
npx playwright test tests/example.spec.ts --debug
Playwright Inspector is useful when the problem can be reproduced locally and you need to step through actions or inspect locators.
–repeat-each
Use:
npx playwright test flaky.spec.ts --repeat-each=20
Repeated execution helps turn an intermittent failure into observable evidence. Avoid interpreting a small number of successful repeats as proof of long-term stability.
With the isolated strategy, retries run after other tests have finished and are executed one by one in a single worker, reducing interference between retries and the rest of the suite. Playwright documents this as an alternative to the default immediate retry strategy.
This can be a useful diagnostic tool for concurrency-related flakes, but it should not become a substitute for fixing shared-state problems.
Limitations and Risks
Traces Can Contain Sensitive Information
Trace Viewer’s Network tab can expose request headers, response headers, request payloads, and response bodies.
Treat trace archives as potentially sensitive CI artifacts. Apply suitable access controls and retention policies, particularly when test systems use real-looking credentials, tokens, customer-like data, or internal APIs.
More Artifacts Create Runtime and Storage Costs
Recording every trace, video, and screenshot from every successful test can be expensive on large suites. Capture detailed artifacts conditionally instead of assuming maximum recording is always desirable.
Retries Change Execution Conditions
Because failed workers are replaced, a retry does not reproduce the original environment perfectly. It is a new observation.
This is why the failing attempt itself is often the most valuable artifact.
A Network Trace Does Not Explain Every Backend Problem
Browser-level network evidence can show what the browser sent and received. It cannot show an internal queue, database lock, service-to-service request, or backend exception that was never returned to the browser.
Correlate browser traces with server logs or distributed tracing when necessary.
A Test Can Expose a Product Flake Rather Than a Test Flake
Do not assume intermittent behavior belongs to automation code.
If the trace proves that the application sometimes leaves an overlay visible, returns inconsistent data, or fails an API request, the automated test may be accurately detecting nondeterministic product behavior.
Conclusion
Effective debugging of flaky Playwright tests is an evidence problem, not a retry-count problem. Use Trace Viewer to reconstruct the failing sequence, screenshots to understand visual state, and network evidence to identify backend or transport failures. Then compare the first failure with the retry to determine which condition changed.
Retries remain useful when they provide another observation. They become harmful when they erase the significance of the first one. A strong CI strategy therefore does both: retain enough evidence to diagnose the failure and keep fail-then-pass tests visible as flaky. With failOnFlakyTests, targeted tracing, web-first assertions, explicit network synchronization, isolated test data, and controlled parallelism, Playwright retries can help investigate instability without converting instability into a false green build.
Codoid’s QA automation services help teams design Playwright suites that surface flakes early, preserve the right evidence, and keep release gates meaningful.
Should I enable trace: 'on' for every Playwright test?
Usually not for routine CI. Playwright warns that tracing every execution is performance-heavy and recommends on-first-retry for CI debugging. During an active flake investigation, retain-on-failure-and-retries can provide more useful failed-versus-passing comparisons.
How many retries should a Playwright test have?
Use the smallest number that serves your diagnostic or resilience policy. A single retry often provides the critical second observation without repeatedly rerunning an unstable test. More retries increase runtime and increase the chance that intermittent instability becomes visually buried. Whatever count you select, report fail-then-pass executions separately from first-attempt passes.
Can Playwright fail CI when a test passes on retry?
Yes. Configure failOnFlakyTests: true or run npx playwright test --fail-on-flaky-tests. Playwright will then return an error when a test is classified as flaky instead of allowing recovered failures to behave like an entirely successful run.
Are screenshots enough for debugging Playwright CI failures?
No. Screenshots are excellent state evidence, but they do not show the chain of events leading to the state. Trace Viewer is more complete because it combines screenshots and DOM snapshots with actions, logs, errors, source code, console messages, and network activity.
Should I use force: true when a Playwright click is flaky?
Only when bypassing the normal actionability behavior is genuinely part of the intended test. A forced click can suppress checks that would otherwise reveal that an overlay or another element is intercepting user interaction. Inspect the trace first and determine why the target cannot receive the event.
How can I tell whether parallel execution causes the flake?
Repeat the test under its normal execution conditions, then repeat it with --workers=1. If failures reliably occur only with multiple workers, investigate shared external state, resource limits, or test-data collisions. Playwright provides single-worker execution specifically for disabling parallelism during this type of diagnosis.
A browser test can be easy to write and difficult to maintain. Consider a test that signs in, creates a workspace, changes its name, and verifies the result. In isolation, the implementation looks straightforward. But what happens when the same test runs across three browsers, four CI machines, and several retry attempts? Who owns the workspace? Can another test change the same account? Does a failed setup leave data behind? Can someone diagnose the failure without rerunning the entire suite? These are questions of Playwright test architecture, not simply questions about selectors. Getting this structure right is what separates a suite that scales from one that collapses under its own maintenance burden. Teams that need expert support in building this foundation can rely on Codoid’s QA automation services to design and implement a maintainable framework.
Those questions are architectural, not simply questions about selectors.
A useful design principle is:
Tests describe behavior. Page objects describe UI interactions. Playwright fixtures own resource lifecycles. Configuration and CI control execution.
This article develops that separation into a practical TypeScript architecture, including test-data ownership, authentication boundaries, parallel execution, and a sharded CI pipeline. Throughout this guide, we will explore how Playwright fixtures solve the problem of resource ownership in a way that keeps tests readable, isolated, and reliable.
The directory names matter less than the responsibilities behind them:
S. No
Layer
Owns
Should not own
1
Specifications
Scenarios and business assertions
Selectors scattered across tests
2
Page and component objects
UI interactions and UI-specific synchronization
Account provisioning or database cleanup
3
API clients
Application requests and response handling
Test-runner lifecycle decisions
4
Fixtures
Resource creation, dependency wiring, and cleanup
Entire business scenarios
5
Configuration and CI
Browsers, scheduling, environments, and artifacts
Hidden changes to what a test verifies
Playwright’s page-object model provides an application-facing interface over browser interactions, while Playwright fixtures provide reusable setup and teardown. The architecture should use those capabilities rather than build another framework around them.
For application specifications, establish one import convention:
import { test, expect } from '../../fixtures/test';
The fixture module becomes the entry point for your suite’s configured test object. Supporting modules can still import Playwright types directly.
As the suite grows, organize specifications by product capability, such as billing, workspaces, or permissions, not by arbitrary categories such as “positive tests” and “negative tests.” For a larger codebase, moving feature-specific page objects and API clients alongside their specifications may improve ownership. Do not introduce that complexity before it solves a real navigation problem.
2. Keep Page Objects Focused on the UI
A useful page object expresses application operations:
await workspacePage.rename('Release planning');
An unhelpful abstraction merely renames Playwright:
await basePage.clickElement('saveButton');
The first communicates intent. The second adds indirection without explaining the application.
Prefer locators based on roles, labels, and explicit test IDs over selectors coupled to incidental DOM structure. Playwright locators resolve the matching element when used, which helps them work with interfaces that rerender.
Put Assertions Where They Explain the Right Contract
“Never put assertions in page objects” is too rigid.
The Saved assertion above defines when rename() has completed successfully. The specification should still own the business claim: the new name appears and survives a reload.
This gives each assertion a clear purpose. The page object checks an interaction’s completion condition; the test checks the behavior being evaluated.
Use Playwright’s retrying assertions for observable UI conditions. An assertion such as await expect(locator).toHaveText(...) waits for the expected state, whereas asserting against an immediately retrieved value does not provide the same retry behavior.
Prefer Composition to a Universal Base Page
When several pages share a navigation bar, date picker, or confirmation dialog, extract a component object rooted at that component’s locator.
A WorkspacePage can contain a NavigationBar and a DeleteDialog. It does not need to inherit from a BasePage that eventually accumulates every interaction in the application.
Keep constructors free of navigation, account creation, and other asynchronous side effects. Constructing an object should not secretly change the test environment.
Playwright fixtures are more than reusable beforeEach hooks. They declare dependencies and establish resource lifetimes.
Playwright initializes non-automatic fixtures when needed. A dependency is initialized before its consumer and torn down afterward. Test-scoped fixtures are recreated for each test execution; worker-scoped fixtures live for the worker process. A worker-scoped fixture cannot depend on a test-scoped fixture.
A practical scope policy is:
S. No
Resource
Recommended scope
1
Built-in browser
Worker, as managed by Playwright
2
Browser context and page
Test
3
Page/component object bound to a page
Test
4
Mutable workspace, order, or document
Test
5
Immutable worker metadata
Worker
6
Reusable account or expensive service
Worker only when its sharing rules are explicit
The built-in page, context, and request fixtures provide test-isolated resources, while the browser is shared to avoid unnecessary startup work.
Separate Resource Operations from Resource Ownership
First, define a small API client. This example assumes an idempotent test-data endpoint that accepts a client-generated workspace ID and returns success only after the resource is ready.
// e2e/api/workspaces-api.ts
import type { APIRequestContext } from '@playwright/test';
export type Workspace = {
id: string;
name: string;
};
export class WorkspacesApi {
constructor(private readonly request: APIRequestContext) {}
async seed(
workspace: Workspace,
namespace: string,
): Promise<void> {
const id = encodeURIComponent(workspace.id);
const response = await this.request.put(
`/__e2e__/workspaces/${id}`,
{
data: {
name: workspace.name,
namespace,
},
},
);
if (!response.ok()) {
throw new Error(
`Seed workspace ${workspace.id}: HTTP ${response.status()}`,
);
}
}
async remove(workspaceId: string): Promise<void> {
const id = encodeURIComponent(workspaceId);
const response = await this.request.delete(
`/__e2e__/workspaces/${id}`,
);
// Repeated cleanup is allowed; unexpected failures are not.
if (!response.ok() && response.status() !== 404) {
throw new Error(
`Delete workspace ${workspaceId}: HTTP ${response.status()}`,
);
}
}
}
Playwright’s API testing support is useful for establishing preconditions and checking backend outcomes without navigating through unrelated UI flows. Keep the behavior under test in the browser: a workspace-renaming test can seed a workspace through an API, but should perform the rename through the UI.
Test-data endpoints should exist only in appropriately isolated test environments. For a remotely accessible environment, protect them with narrowly scoped authorization rather than exposing administrative functionality publicly.
The worker namespace records ownership, not test identity. parallelIndex identifies a worker slot and remains stable when that slot’s process is restarted; workerIndex identifies the process and changes on restart. Neither should be treated as globally unique across independent CI jobs.
Each workspace receives its own identifier. Consequently, multiple tests can use the same friendly workspace name without selecting or deleting each other’s records, provided the application operations remain scoped to the workspace ID.
The metadata attachment connects a failure to its backend resource without attaching credentials or the entire application response. Playwright exposes attachment APIs through TestInfo.
Cleanup Needs Both a Normal Path and a Recovery Path
Allocating the ID before seeding allows the fixture to attempt cleanup even when the seed request fails after the server has created the resource.
However, finally is not a distributed cleanup guarantee. A killed process, canceled machine, or delayed backend operation can still leave resources behind. For shared test environments, add an expiration policy or a cleanup service that removes old resources by ownership namespace.
Also keep cleanup failures visible. For fixtures that allocate several resources, release them in reverse dependency order and preserve the original failure when reporting additional cleanup errors.
A resource needs an owner, an identifier, and a cleanup policy, not merely a creation helper.
The test states its precondition, action, and persistence check. It does not need to know how the workspace was created or how it will be removed.
Notice that the page-object fixture does not automatically navigate. Navigation remains explicit because it helps the reader understand the scenario. Playwright fixtures should eliminate lifecycle repetition without hiding meaningful test steps.
Avoid turning the entire scenario into something like:
await workspaceFlows.verifyRenameWorks();
That may reduce the line count, but it also removes the test’s explanation of what “works” means.
5. Treat Authentication and Backend Isolation Separately
A new browser context isolates browser state. It does not create a new database, workspace, shopping cart, or account.
Playwright supports loading saved authentication state into fresh contexts. Its authentication guidance distinguishes shared accounts for non-interfering tests from separate worker accounts for tests that change shared server-side state.
Choose the boundary according to what the tests mutate:
S. No
Strategy
Appropriate use
1
Shared saved authentication state
Tests can safely use the same account concurrently
2
Account per worker
Account reuse is safe within a worker and mutable state is reset or independently scoped
3
Account or tenant per test
Tests change permissions, credentials, account settings, or other destructive state
For worker authentication, create a worker-scoped account lease and authentication-state fixture, then have the test-scoped storageState fixture provide that state to each fresh context. Do not share a live Page merely to avoid logging in again.
A worker account prevents concurrent workers from changing the same account, but it does not reset changes between successive tests using that account. Reset those changes or allocate more narrowly.
Keep saved authentication state out of source control and ordinary report uploads; it can contain credentials sufficient to impersonate a test account.
There is another important distinction: the built-in request fixture is separate from the browser context, while page.request and context.request share that browser context’s cookie storage. Logging in through an independent API context does not automatically authenticate an already-created browser context. Transfer authentication state deliberately.
Use Setup Projects for Visible Prerequisites
For reusable prerequisites such as generating shared read-only authentication state, a setup project with project dependencies can make setup visible in reports and traces.
Do not interpret a setup project as “exactly once across the entire CI system.” Shard filtering selects primary tests, and their project dependencies also run. Independent shard invocations therefore need setup that tolerates repetition.
Database migrations against a shared environment, for example, usually belong in a coordinated deployment stage rather than an uncoordinated setup task on every shard.
6. Design for Parallel Execution Before Increasing Concurrency
Parallel execution is easier to introduce when tests already own their state.
Playwright runs test files in parallel by default, while tests within a file normally run in order. fullyParallel: true allows tests within files to run in parallel too. Workers are separate processes, and a failure causes the affected worker to be replaced.
Three controls are often confused:
Workers control concurrent execution within one Playwright invocation.
Shards split selected tests across separate invocations, typically on separate CI machines.
Projects define configurations such as Chromium, Firefox, WebKit, devices, or environments. Multiple projects in one invocation do not each receive an additional independent allocation of the global worker limit.
For example, four simultaneously running shard jobs with two workers each provide an upper bound of approximately eight active test workers. Adding a separate browser dimension to the CI matrix creates more jobs and changes that calculation.
This is a capacity estimate, not a promise of proportional speedup. Startup costs, long tests, database contention, and runner limits still matter.
Shard Balance Depends on Test Structure
With fully parallel execution, Playwright can distribute individual tests across shards. Without it, sharding generally operates at file granularity. Test-level distribution helps avoid placing one large file entirely on one shard, but balancing test counts does not guarantee equal execution time.
Measure the slowest shard, not just total test duration.
Do Not Use Serial Execution to Conceal Dependencies
A sequence such as “create account,” “update account,” and “delete account” should usually be one test with explicit stages, or three independently provisioned tests.
In a serial group, a failure skips later tests, and retries rerun the group together. That behavior can be appropriate for a genuinely indivisible workflow, but it is a poor substitute for resource isolation.
For a truly exclusive external resource, use an explicitly coordinated strategy across every job that can access it. Ordering tests inside one process does not coordinate independent CI runs.
7. Make Configuration an Explicit Execution Policy
A configuration file should explain how the suite runs without changing the scenario’s meaning:
These are deliberate starting choices, not universal optimums.
Start with conservative CI concurrency. Playwright recommends one worker on CI for stability and reproducibility, with sharding as a way to distribute execution more widely. Increase workers only after measuring the runner and application under load.
Use retries as diagnostic evidence. Playwright marks a test that fails initially and passes on retry as flaky. failOnFlakyTests makes those outcomes fail the run, so retries can gather evidence without silently weakening the quality gate. Teams adopting this incrementally can initially track flakes before enforcing the gate.
Choose trace retention intentionally. retain-on-failure records every attempt and keeps failed attempts. on-first-retry records only the first retry, which reduces recording work but does not capture the original failed attempt.
Make application readiness meaningful. Playwright’s webServer can launch the app and wait for an endpoint. In this example, start:e2e must start the test deployment, and /health should report readiness only after required dependencies are usable. Disabling server reuse on CI also prevents accidentally accepting an unrelated existing process.
8. Build CI Around Reproducibility and Failure Evidence
A reliable CI pipeline needs more than a browser-test command. It should install locked dependencies, check the test code, start the correct application, preserve diagnostic output, and retain the original test-job result.
Playwright transpiles TypeScript but does not perform full type checking. Run the TypeScript compiler separately, and ensure the selected tsconfig.json includes both the E2E sources and Playwright configuration. Linting should also catch missing awaits, for example through @typescript-eslint/no-floating-promises.
The following workflow assumes the repository provides lint, build, and start:e2e scripts. Each test job starts its own disposable local application. It runs Chromium across four shards and combines their blob reports afterward.
The workflow does not use continue-on-error or append || true to the test command. A failing shard remains a failing job.
Report collection is allowed after ordinary test failures, and the merge job can produce diagnostic output even when a shard failed. Blob reports contain test results and attachments, including traces, so they are suitable for combining sharded runs.
Keep the test jobs as required checks. A report-generation job is not a replacement for their exit statuses.
Artifact names include the workflow attempt to avoid silently mixing separate attempts. Because the completeness check expects all four reports from that attempt, rerun the entire workflow when generating a new complete merged report.
For a scheduled cross-browser run, install all required browsers and remove the Chromium project filter. As the suite grows, move repeated type checking, linting, and building into prerequisite jobs where doing so improves cost without weakening reproducibility.
Protect the Execution Boundary
The example uses readable major-version action references. In a hardened repository, pin approved actions to full commit SHAs and update them through a controlled process. Keep credentials narrowly scoped, restrict token permissions, and do not expose privileged execution or secrets to untrusted pull-request code.
Treat traces and reports as potentially sensitive application data, not automatically harmless build output. Set access and retention policies accordingly.
9. Keep the Architecture Maintainable as It Grows
The architecture should make common changes local.
A changed button label should usually affect a page or component object. A new workspace-provisioning mechanism should affect the API client and fixture. A larger browser matrix should affect configuration and CI, not business assertions.
Watch for abstractions that break those boundaries. A page object that reads CI environment variables is taking on execution policy. A fixture that automatically performs an entire checkout is concealing scenario behavior. A worker-scoped mutable object is introducing shared state that reviewers must reason about.
For an existing suite, migrate incrementally. Establish the fixture import boundary, move paired setup and teardown into fixtures, isolate mutable resources, and then enable broader parallel execution. Do not treat a large folder reorganization as proof that the architecture has improved.
Make debugging part of normal development. A focused test can be run directly, repeated, or executed with a different worker count through Playwright’s CLI. These commands help investigate repeatability and concurrency sensitivity, although a successful repeated run is not proof that a test is deterministic.
# Run one specification.
npx playwright test e2e/specs/workspaces/rename-workspace.spec.ts \
--project=chromium
# Investigate repeatability with retries disabled.
npx playwright test e2e/specs/workspaces/rename-workspace.spec.ts \
--project=chromium --repeat-each=20 --retries=0
# Compare behavior under greater concurrency.
npx playwright test --project=chromium --workers=4 --retries=0
Track first-attempt pass rate, flaky outcomes, fixture setup time, the slowest shard, and the effort required to diagnose a failure. Those measures give the team a more useful maintenance picture than test count alone.
Maintainable Playwright automation starts with explicit ownership.A test should own the behavior it verifies. A page object should own the application’s UI vocabulary. Playwright fixtures should own the lifetime of every resource they provide. Parallel execution should operate on independently scoped state, and CI should preserve both reproducibility and failure evidence.
The goal is not the shortest test file or the most elaborate framework. It is a suite in which a test remains understandable, and its result remains trustworthy, when it runs alone, alongside hundreds of other tests, after a worker restart, or across several CI machines.Codoid’s automation testing services can help you design and implement a maintainable Playwright test architecture tailored to your team’s workflow.
Playwright test architecture is the way a test suite is organized into distinct layers with clear ownership. Tests describe behavior, page objects describe UI interactions, fixtures own resource lifecycles, and configuration plus CI control execution. A well-designed architecture keeps each layer focused so that a change to a button label affects only a page object, while a change to a browser matrix affects only configuration and CI. This separation is what allows a suite to remain understandable and trustworthy as it grows from a handful of tests to hundreds running across multiple CI machines.
Why does Playwright test architecture matter for maintainability?
Without a clear architecture, tests accumulate shared state, duplicated selectors, and hidden dependencies. Failures become difficult to diagnose, and parallel execution becomes unsafe. A deliberate architecture makes common changes local. When a control name changes, only the page object needs updating. When a new provisioning mechanism is introduced, only the API client and fixture are affected. When the browser matrix expands, only the configuration and CI workflow change. This reduces maintenance effort and keeps test intent visible to reviewers.
What is the difference between fixtures and page objects in Playwright?
Page objects own the application's UI vocabulary. They expose operations such as rename() or open() and encapsulate locators and UI-specific synchronization. Fixtures own resource lifecycles. They create, wire, and clean up dependencies such as browser contexts, test data, API clients, and authentication state. A page object answers "how do I interact with this screen," while a fixture answers "who creates this resource and when is it removed." Both are necessary, and combining them into one layer usually makes both harder to maintain.
What is the recommended scope for Playwright fixtures?
The built-in browser should use worker scope, since Playwright manages it and sharing it avoids unnecessary startup work. Browser context, page, and page objects bound to a page should use test scope so each test receives isolated resources. Mutable workspaces, orders, or documents should use test scope. Immutable worker metadata such as a run namespace should use worker scope. Reusable accounts or expensive shared services should use worker scope only when their sharing rules are explicit and safe. Start with test scope by default and promote to worker scope only when the sharing rules are clearly understood.
How should test data be isolated in a Playwright test architecture?
Each test should own its data. Generate a unique identifier for every resource the test creates, seed it through an API before the test runs, and remove it afterward using a fixture. This prevents tests from selecting or deleting each other's records, even when running in parallel across workers and CI shards. A useful pattern is to allocate the resource identifier before seeding, so the fixture can still attempt cleanup if the seed request fails partway through. For shared environments, add an expiration policy or cleanup service to handle resources left behind by killed processes.
How does Playwright test architecture support parallel execution?
Parallel execution is safe when tests already own their state. Playwright runs test files in parallel by default, and fullyParallel allows tests within a file to run in parallel as well. Workers are separate processes, so a failure replaces only the affected worker. Sharding splits selected tests across separate CI machines. Projects define configurations such as browsers or devices. Because each test owns its own data and does not depend on execution order, increasing workers or adding shards does not introduce shared-state failures. Measure the slowest shard rather than total test duration when tuning concurrency.
What is the difference between workers, shards, and projects in Playwright?
Workers control concurrent execution within a single Playwright invocation. Shards split selected tests across separate invocations, typically on separate CI machines. Projects define configurations such as Chromium, Firefox, WebKit, devices, or environments. Multiple projects in one invocation do not each receive an additional independent allocation of the global worker limit, so adding a browser dimension to the CI matrix creates more jobs and changes the capacity calculation. Understanding these three controls prevents over-provisioning and keeps pipeline costs predictable.