QA AND TEST AUTOMATION · PART 5 · UI WEB AUTOMATION · DESIGN · 55 OF 112

Test Fixtures and Reusing Login State in Playwright

Removing repeated setup from UI tests: custom Playwright fixtures (an automatic data reset and a ready ProductsPage), and logging in once with a setup project that saves storageState, which for ShopRung holds the token in localStorage. Run for real: 2 passed in 2.0 s. Also per-role states, API logins, keeping state files out of Git, and the Selenium and pytest equivalents.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Custom fixtures with use()
  • auto reset
  • log in once
  • storageState
  • setup project dependency
  • roles and expiry

Notes

What fixtures are

You have already used fixtures: page, request, context and browser. A fixture is named setup that a test asks for by listing it as a parameter. Playwright creates only the fixtures a test asks for, gives them to the test, and cleans them up afterwards. Page is a fresh tab in a fresh context, an isolated browser profile with its own cookies and storage. Now you will write your own.

Built-in fixtures
page      fresh tab per test
context   isolated browser
          profile per test
browser   shared per worker
request   API client

a test asks: async ({ page,
  request }) => { ... }
only what is asked for is
  created, then cleaned up

Custom fixtures

Extend the base test with your own fixtures. Clean shop resets ShopRung through the API, then calls use, which runs the test; anything after use is teardown. It is marked auto, so it runs for every test without being asked for. Products creates the page object from the last episode and opens the page, so a test that asks for products gets a ready page object. Tests import this extended test instead of the default one.

fx/fixtures.ts
export const test = base.extend<F>({
  cleanShop: [async ({ request },
      use) => {
    await request.post(
      "/api/test/reset");
    await use();
  }, { auto: true }],
  products: async ({ page }, use) => {
    const p = new ProductsPage(page);
    await p.open(); await use(p);
  }, });

Log in once

Now log in once. A setup file logs in through the real UI, exactly like a test: fill email and password, click log in, wait until the user name is visible. Then it saves the context's storage state to a JSON file. Storage state is the browser's cookies and local storage for each site. Waiting for the user name first matters: save too early and you save a logged out state.

fx/auth.setup.ts
setup("log in as alice",
  async ({ page }) => {
  await page.goto("/#/login");
  await page.getByLabel("Email")...
  await page.getByLabel("Password")...
  await page.getByRole("button",
    { name: "Log in" }).click();
  await expect(page.getByTestId(
    "user-name")).toBeVisible();
  await page.context().storageState(
    { path: AUTH_FILE }); });

What gets saved

We looked inside the saved file. ShopRung's cookies list is empty, and under the site's origin, local storage holds shoprung dot token and shoprung dot user, which is where the app keeps its login. Many apps use cookies instead; storage state saves both, so the approach works either way. The file holds a real, working token, so add the auth folder to git ignore.

alice.json (shape)
{
  "cookies": [],
  "origins": [{
    "origin": "http://localhost:...",
    "localStorage": [
      { "name": "shoprung.token" },
      { "name": "shoprung.user" }
    ] }]
}
a real login token: keep it
  out of Git (.gitignore)

Wire it up

Wire it up in the config. A setup project matches files ending in setup dot ts. The browser project lists setup as a dependency, so setup runs first, and sets storage state to the saved file, so every test's new context starts with Alice already logged in. You can also choose the state per file with test dot use, which is handy when only some tests need a login.

playwright.config.ts
projects: [
  { name: "setup",
    testMatch: /.*\.setup\.ts/ },
  { name: "chromium",
    dependencies: ["setup"],
    use: { storageState:
      "playwright/.auth/alice.json" }
  },
]
or per file: test.use({
  storageState: "..." })

The test

The test asks for products and page. The reset ran automatically, the products page is open, and the header already says hi, Alice Shah, without touching the login form. It adds the notebook and expects a cart count of one. Our run: the setup project and the test, two passed in two seconds. With a hundred tests, the login form runs once instead of a hundred times.

fx/cart.spec.ts
import { test, expect }
  from "./fixtures";
test.use({ storageState: ALICE });
test("logged-in user adds",
  async ({ products, page }) => {
  await expect(page.getByTestId(
    "user-name")).toHaveText(
    "Hi, Alice Shah");
  await products.addToCart(
    "Clean Code Notebook");
  ... cart-count toHaveText("1")

Variations

Variations. Save one state file per role, like customer and admin, and pick per test. Log in through the API in setup for extra speed, then set the cookie or storage. Tests that change the account, such as changing the password, need their own user, or they break everyone else. Tokens expire, ShopRung's after two hours, so regenerate state on every run. And keep one or two real UI login tests, because the login page itself still needs testing.

Real-world options
  • one state file per role: customer.json, admin.json
  • log in via API (faster): get the token, then set storage or cookies in setup
  • tests that CHANGE the account need their own user
  • tokens expire (ShopRung: 2 h) → regenerate each run
  • keep 1-2 real UI login tests

Other tools

The same ideas exist elsewhere. Pytest fixtures, which you met in Part four, can yield a Selenium driver and quit it, with session scope for expensive setup. Selenium can skip the login form by getting a token through the API, then adding a cookie with the driver, or setting local storage with JavaScript, after opening the site. In JUnit five, extensions and before each helpers play the role of fixtures.

Equivalents
  • pytest fixtures (Part 4): a driver fixture that yields and quits; scope="session" for expensive setup
  • Selenium: log in via API, then driver.manage().addCookie() or set localStorage with JS
  • JUnit 5: extensions, @BeforeEach helpers

Common mistakes

Setup mistakes. Logging in through the UI in every test. Saving storage state before the login has actually finished. Committing auth JSON files with real tokens. One shared user that tests modify, so they break each other in parallel. Giant fixtures that set up everything for every test. And hidden setup so clever that nobody can find where data comes from; name fixtures clearly and keep them small.

Avoid these
  • UI login in every test
  • saving state before login finished
  • committing auth JSON files
  • one shared user that tests modify
  • giant fixtures doing everything for everyone
  • hidden setup no one can find

Say it like this

In the interview: a setup project logs in once per role, through the UI or the API, and saves storage state, meaning cookies and local storage. Test projects depend on setup and load that state, so every test starts logged in in its own isolated context. Custom fixtures handle data reset and page objects. State files are git ignored and regenerated each run, and a couple of real UI login tests remain.

In the interview
  • "A setup project logs in once
  • per role, via UI or API, and saves storageState: cookies
  • and localStorage. Test
  • projects depend on it and load
  • the state, so tests start
  • logged in. Custom fixtures
  • handle reset and page objects.
  • State files are git-ignored and regenerated each run."

Interview questions

Q1What is a Playwright fixture?

Named, on-demand setup and teardown (page, request, or your own via test.extend) that a test receives by listing it as a parameter.

Q2What does use() do in a custom fixture?

It hands the fixture value to the test and waits for the test to finish; code after use() is teardown.

Q3What is storageState?

A snapshot of a browser context's cookies and localStorage per origin, saved to JSON and loaded into new contexts to restore a logged-in session.

Q4How do you log in once for all Playwright tests?

A setup project logs in and saves storageState; other projects declare it as a dependency and set use.storageState to the saved file.

Q5What is an automatic fixture?

A fixture with { auto: true } that runs for every test without being requested, such as a data reset or logging.

Q6How do you handle multiple roles?

Save one storage state per role (customer, admin) and choose per project or per file with test.use({ storageState }).

Q7How can Selenium skip the login form?

Get a session or token through the API, open the site, then add the cookie with driver.manage().addCookie() or set localStorage via JavaScript.

Q8Why keep some UI login tests?

Because the login page itself (validation, errors, redirects) still needs testing; only other tests skip it.