tests/login.spec.js
import { test, expect } from "@playwright/test";
import { login, USERS } from "./fixtures.js";
// These tests are about signing in, so they start signed out.
test.use({ storageState: { cookies: [], origins: [] } });
test("a failed sign-in shows a generic error", async ({ page }, testInfo) => {
// Not Alice: failed logins count toward a per-email lockout, and repeated
// runs would lock out the user every other test signs in as.
const email = `nobody-${testInfo.repeatEachIndex}-${testInfo.retry}@example.com`;
await login(page, { email, password: "nope" });
// The server says the same thing for an unknown email and a wrong
// password, so the form can't be used to discover who has an account.
await expect(page.getByRole("alert")).toHaveText("Invalid email or password");
await expect(page.getByRole("list", { name: "Your orders" })).toBeHidden();
});
test("signing in shows the user's own orders", async ({ page }) => {
await login(page, USERS.bob);
await expect(page.getByText("Bob", { exact: true })).toBeVisible();
await expect(page.getByRole("list", { name: "Your orders" }).getByRole("listitem")).toHaveCount(1);
});
test("the session cookie is HttpOnly and SameSite", async ({ page, context }) => {
await login(page, USERS.bob);
await expect(page.getByRole("list", { name: "Your orders" })).toBeVisible();
const sid = (await context.cookies()).find((c) => c.name === "sid");
expect(sid).toMatchObject({ httpOnly: true, sameSite: "Lax" });
// ...and so page JavaScript (and any XSS) cannot read it.
expect(await page.evaluate(() => document.cookie)).not.toContain("sid=");
});
test("sign out ends the session on the server too", async ({ page }) => {
await login(page, USERS.bob);
await page.getByRole("button", { name: "Sign out" }).click();
await expect(page.getByRole("heading", { name: "Sign in" })).toBeVisible();
expect((await page.request.get("/api/me")).status()).toBe(401);
});
test("login page looks right @visual", async ({ page }) => {
await page.goto("/");
await expect(page.getByRole("heading", { name: "Sign in" })).toBeVisible();
await expect(page).toHaveScreenshot("login.png");
});