選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

test-quality.md 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. # Test Quality Definition of Done
  2. ## Principle
  3. Tests must be deterministic, isolated, explicit, focused, and fast. Every test should execute in under 1.5 minutes, contain fewer than 300 lines, avoid hard waits and conditionals, keep assertions visible in test bodies, and clean up after itself for parallel execution.
  4. ## Rationale
  5. Quality tests provide reliable signal about application health. Flaky tests erode confidence and waste engineering time. Tests that use hard waits (`waitForTimeout(3000)`) are non-deterministic and slow. Tests with hidden assertions or conditional logic become unmaintainable. Large tests (>300 lines) are hard to understand and debug. Slow tests (>1.5 min) block CI pipelines. Self-cleaning tests prevent state pollution in parallel runs.
  6. ## Pattern Examples
  7. ### Example 1: Deterministic Test Pattern
  8. **Context**: When writing tests, eliminate all sources of non-determinism: hard waits, conditionals controlling flow, try-catch for flow control, and random data without seeds.
  9. **Implementation**:
  10. ```typescript
  11. // ❌ BAD: Non-deterministic test with conditionals and hard waits
  12. test('user can view dashboard - FLAKY', async ({ page }) => {
  13. await page.goto('/dashboard');
  14. await page.waitForTimeout(3000); // NEVER - arbitrary wait
  15. // Conditional flow control - test behavior varies
  16. if (await page.locator('[data-testid="welcome-banner"]').isVisible()) {
  17. await page.click('[data-testid="dismiss-banner"]');
  18. await page.waitForTimeout(500);
  19. }
  20. // Try-catch for flow control - hides real issues
  21. try {
  22. await page.click('[data-testid="load-more"]');
  23. } catch (e) {
  24. // Silently continue - test passes even if button missing
  25. }
  26. // Random data without control
  27. const randomEmail = `user${Math.random()}@example.com`;
  28. await expect(page.getByText(randomEmail)).toBeVisible(); // Will fail randomly
  29. });
  30. // ✅ GOOD: Deterministic test with explicit waits
  31. test('user can view dashboard', async ({ page, apiRequest }) => {
  32. const user = createUser({ email: 'test@example.com', hasSeenWelcome: true });
  33. // Setup via API (fast, controlled)
  34. await apiRequest.post('/api/users', { data: user });
  35. // Network-first: Intercept BEFORE navigate
  36. const dashboardPromise = page.waitForResponse((resp) => resp.url().includes('/api/dashboard') && resp.status() === 200);
  37. await page.goto('/dashboard');
  38. // Wait for actual response, not arbitrary time
  39. const dashboardResponse = await dashboardPromise;
  40. const dashboard = await dashboardResponse.json();
  41. // Explicit assertions with controlled data
  42. await expect(page.getByText(`Welcome, ${user.name}`)).toBeVisible();
  43. await expect(page.getByTestId('dashboard-items')).toHaveCount(dashboard.items.length);
  44. // No conditionals - test always executes same path
  45. // No try-catch - failures bubble up clearly
  46. });
  47. // Cypress equivalent
  48. describe('Dashboard', () => {
  49. it('should display user dashboard', () => {
  50. const user = createUser({ email: 'test@example.com', hasSeenWelcome: true });
  51. // Setup via task (fast, controlled)
  52. cy.task('db:seed', { users: [user] });
  53. // Network-first interception
  54. cy.intercept('GET', '**/api/dashboard').as('getDashboard');
  55. cy.visit('/dashboard');
  56. // Deterministic wait for response
  57. cy.wait('@getDashboard').then((interception) => {
  58. const dashboard = interception.response.body;
  59. // Explicit assertions
  60. cy.contains(`Welcome, ${user.name}`).should('be.visible');
  61. cy.get('[data-cy="dashboard-items"]').should('have.length', dashboard.items.length);
  62. });
  63. });
  64. });
  65. ```
  66. **Key Points**:
  67. - Replace `waitForTimeout()` with `waitForResponse()` or element state checks
  68. - Never use if/else to control test flow - tests should be deterministic
  69. - Avoid try-catch for flow control - let failures bubble up clearly
  70. - Use factory functions with controlled data, not `Math.random()`
  71. - Network-first pattern prevents race conditions
  72. ### Example 2: Isolated Test with Cleanup
  73. **Context**: When tests create data, they must clean up after themselves to prevent state pollution in parallel runs. Use fixture auto-cleanup or explicit teardown.
  74. **Implementation**:
  75. ```typescript
  76. // ❌ BAD: Test leaves data behind, pollutes other tests
  77. test('admin can create user - POLLUTES STATE', async ({ page, apiRequest }) => {
  78. await page.goto('/admin/users');
  79. // Hardcoded email - collides in parallel runs
  80. await page.fill('[data-testid="email"]', 'newuser@example.com');
  81. await page.fill('[data-testid="name"]', 'New User');
  82. await page.click('[data-testid="create-user"]');
  83. await expect(page.getByText('User created')).toBeVisible();
  84. // NO CLEANUP - user remains in database
  85. // Next test run fails: "Email already exists"
  86. });
  87. // ✅ GOOD: Test cleans up with fixture auto-cleanup
  88. // playwright/support/fixtures/database-fixture.ts
  89. import { test as base } from '@playwright/test';
  90. import { deleteRecord, seedDatabase } from '../helpers/db-helpers';
  91. type DatabaseFixture = {
  92. seedUser: (userData: Partial<User>) => Promise<User>;
  93. };
  94. export const test = base.extend<DatabaseFixture>({
  95. seedUser: async ({}, use) => {
  96. const createdUsers: string[] = [];
  97. const seedUser = async (userData: Partial<User>) => {
  98. const user = await seedDatabase('users', userData);
  99. createdUsers.push(user.id); // Track for cleanup
  100. return user;
  101. };
  102. await use(seedUser);
  103. // Auto-cleanup: Delete all users created during test
  104. for (const userId of createdUsers) {
  105. await deleteRecord('users', userId);
  106. }
  107. createdUsers.length = 0;
  108. },
  109. });
  110. // Use the fixture
  111. test('admin can create user', async ({ page, seedUser }) => {
  112. // Create admin with unique data
  113. const admin = await seedUser({
  114. email: faker.internet.email(), // Unique each run
  115. role: 'admin',
  116. });
  117. await page.goto('/admin/users');
  118. const newUserEmail = faker.internet.email(); // Unique
  119. await page.fill('[data-testid="email"]', newUserEmail);
  120. await page.fill('[data-testid="name"]', 'New User');
  121. await page.click('[data-testid="create-user"]');
  122. await expect(page.getByText('User created')).toBeVisible();
  123. // Verify in database
  124. const createdUser = await seedUser({ email: newUserEmail });
  125. expect(createdUser.email).toBe(newUserEmail);
  126. // Auto-cleanup happens via fixture teardown
  127. });
  128. // Cypress equivalent with explicit cleanup
  129. describe('Admin User Management', () => {
  130. const createdUserIds: string[] = [];
  131. afterEach(() => {
  132. // Cleanup: Delete all users created during test
  133. createdUserIds.forEach((userId) => {
  134. cy.task('db:delete', { table: 'users', id: userId });
  135. });
  136. createdUserIds.length = 0;
  137. });
  138. it('should create user', () => {
  139. const admin = createUser({ role: 'admin' });
  140. const newUser = createUser(); // Unique data via faker
  141. cy.task('db:seed', { users: [admin] }).then((result: any) => {
  142. createdUserIds.push(result.users[0].id);
  143. });
  144. cy.visit('/admin/users');
  145. cy.get('[data-cy="email"]').type(newUser.email);
  146. cy.get('[data-cy="name"]').type(newUser.name);
  147. cy.get('[data-cy="create-user"]').click();
  148. cy.contains('User created').should('be.visible');
  149. // Track for cleanup
  150. cy.task('db:findByEmail', newUser.email).then((user: any) => {
  151. createdUserIds.push(user.id);
  152. });
  153. });
  154. });
  155. ```
  156. **Key Points**:
  157. - Use fixtures with auto-cleanup via teardown (after `use()`)
  158. - Track all created resources in array during test execution
  159. - Use `faker` for unique data - prevents parallel collisions
  160. - Cypress: Use `afterEach()` with explicit cleanup
  161. - Never hardcode IDs or emails - always generate unique values
  162. ### Example 3: Explicit Assertions in Tests
  163. **Context**: When validating test results, keep assertions visible in test bodies. Never hide assertions in helper functions - this obscures test intent and makes failures harder to diagnose.
  164. **Implementation**:
  165. ```typescript
  166. // ❌ BAD: Assertions hidden in helper functions
  167. // helpers/api-validators.ts
  168. export async function validateUserCreation(response: Response, expectedEmail: string) {
  169. const user = await response.json();
  170. expect(response.status()).toBe(201);
  171. expect(user.email).toBe(expectedEmail);
  172. expect(user.id).toBeTruthy();
  173. expect(user.createdAt).toBeTruthy();
  174. // Hidden assertions - not visible in test
  175. }
  176. test('create user via API - OPAQUE', async ({ request }) => {
  177. const userData = createUser({ email: 'test@example.com' });
  178. const response = await request.post('/api/users', { data: userData });
  179. // What assertions are running? Have to check helper.
  180. await validateUserCreation(response, userData.email);
  181. // When this fails, error is: "validateUserCreation failed" - NOT helpful
  182. });
  183. // ✅ GOOD: Assertions explicit in test
  184. test('create user via API', async ({ request }) => {
  185. const userData = createUser({ email: 'test@example.com' });
  186. const response = await request.post('/api/users', { data: userData });
  187. // All assertions visible - clear test intent
  188. expect(response.status()).toBe(201);
  189. const createdUser = await response.json();
  190. expect(createdUser.id).toBeTruthy();
  191. expect(createdUser.email).toBe(userData.email);
  192. expect(createdUser.name).toBe(userData.name);
  193. expect(createdUser.role).toBe('user');
  194. expect(createdUser.createdAt).toBeTruthy();
  195. expect(createdUser.isActive).toBe(true);
  196. // When this fails, error is: "Expected role to be 'user', got 'admin'" - HELPFUL
  197. });
  198. // ✅ ACCEPTABLE: Helper for data extraction, NOT assertions
  199. // helpers/api-extractors.ts
  200. export async function extractUserFromResponse(response: Response): Promise<User> {
  201. const user = await response.json();
  202. return user; // Just extracts, no assertions
  203. }
  204. test('create user with extraction helper', async ({ request }) => {
  205. const userData = createUser({ email: 'test@example.com' });
  206. const response = await request.post('/api/users', { data: userData });
  207. // Extract data with helper (OK)
  208. const createdUser = await extractUserFromResponse(response);
  209. // But keep assertions in test (REQUIRED)
  210. expect(response.status()).toBe(201);
  211. expect(createdUser.email).toBe(userData.email);
  212. expect(createdUser.role).toBe('user');
  213. });
  214. // Cypress equivalent
  215. describe('User API', () => {
  216. it('should create user with explicit assertions', () => {
  217. const userData = createUser({ email: 'test@example.com' });
  218. cy.request('POST', '/api/users', userData).then((response) => {
  219. // All assertions visible in test
  220. expect(response.status).to.equal(201);
  221. expect(response.body.id).to.exist;
  222. expect(response.body.email).to.equal(userData.email);
  223. expect(response.body.name).to.equal(userData.name);
  224. expect(response.body.role).to.equal('user');
  225. expect(response.body.createdAt).to.exist;
  226. expect(response.body.isActive).to.be.true;
  227. });
  228. });
  229. });
  230. // ✅ GOOD: Parametrized tests for soft assertions (bulk validation)
  231. test.describe('User creation validation', () => {
  232. const testCases = [
  233. { field: 'email', value: 'test@example.com', expected: 'test@example.com' },
  234. { field: 'name', value: 'Test User', expected: 'Test User' },
  235. { field: 'role', value: 'admin', expected: 'admin' },
  236. { field: 'isActive', value: true, expected: true },
  237. ];
  238. for (const { field, value, expected } of testCases) {
  239. test(`should set ${field} correctly`, async ({ request }) => {
  240. const userData = createUser({ [field]: value });
  241. const response = await request.post('/api/users', { data: userData });
  242. const user = await response.json();
  243. // Parametrized assertion - still explicit
  244. expect(user[field]).toBe(expected);
  245. });
  246. }
  247. });
  248. ```
  249. **Key Points**:
  250. - Never hide `expect()` calls in helper functions
  251. - Helpers can extract/transform data, but assertions stay in tests
  252. - Parametrized tests are acceptable for bulk validation (still explicit)
  253. - Explicit assertions make failures actionable: "Expected X, got Y"
  254. - Hidden assertions produce vague failures: "Helper function failed"
  255. ### Example 4: Test Length Limits
  256. **Context**: When tests grow beyond 300 lines, they become hard to understand, debug, and maintain. Refactor long tests by extracting setup helpers, splitting scenarios, or using fixtures.
  257. **Implementation**:
  258. ```typescript
  259. // ❌ BAD: 400-line monolithic test (truncated for example)
  260. test('complete user journey - TOO LONG', async ({ page, request }) => {
  261. // 50 lines of setup
  262. const admin = createUser({ role: 'admin' });
  263. await request.post('/api/users', { data: admin });
  264. await page.goto('/login');
  265. await page.fill('[data-testid="email"]', admin.email);
  266. await page.fill('[data-testid="password"]', 'password123');
  267. await page.click('[data-testid="login"]');
  268. await expect(page).toHaveURL('/dashboard');
  269. // 100 lines of user creation
  270. await page.goto('/admin/users');
  271. const newUser = createUser();
  272. await page.fill('[data-testid="email"]', newUser.email);
  273. // ... 95 more lines of form filling, validation, etc.
  274. // 100 lines of permissions assignment
  275. await page.click('[data-testid="assign-permissions"]');
  276. // ... 95 more lines
  277. // 100 lines of notification preferences
  278. await page.click('[data-testid="notification-settings"]');
  279. // ... 95 more lines
  280. // 50 lines of cleanup
  281. await request.delete(`/api/users/${newUser.id}`);
  282. // ... 45 more lines
  283. // TOTAL: 400 lines - impossible to understand or debug
  284. });
  285. // ✅ GOOD: Split into focused tests with shared fixture
  286. // playwright/support/fixtures/admin-fixture.ts
  287. export const test = base.extend({
  288. adminPage: async ({ page, request }, use) => {
  289. // Shared setup: Login as admin
  290. const admin = createUser({ role: 'admin' });
  291. await request.post('/api/users', { data: admin });
  292. await page.goto('/login');
  293. await page.fill('[data-testid="email"]', admin.email);
  294. await page.fill('[data-testid="password"]', 'password123');
  295. await page.click('[data-testid="login"]');
  296. await expect(page).toHaveURL('/dashboard');
  297. await use(page); // Provide logged-in page
  298. // Cleanup handled by fixture
  299. },
  300. });
  301. // Test 1: User creation (50 lines)
  302. test('admin can create user', async ({ adminPage, seedUser }) => {
  303. await adminPage.goto('/admin/users');
  304. const newUser = createUser();
  305. await adminPage.fill('[data-testid="email"]', newUser.email);
  306. await adminPage.fill('[data-testid="name"]', newUser.name);
  307. await adminPage.click('[data-testid="role-dropdown"]');
  308. await adminPage.click('[data-testid="role-user"]');
  309. await adminPage.click('[data-testid="create-user"]');
  310. await expect(adminPage.getByText('User created')).toBeVisible();
  311. await expect(adminPage.getByText(newUser.email)).toBeVisible();
  312. // Verify in database
  313. const created = await seedUser({ email: newUser.email });
  314. expect(created.role).toBe('user');
  315. });
  316. // Test 2: Permission assignment (60 lines)
  317. test('admin can assign permissions', async ({ adminPage, seedUser }) => {
  318. const user = await seedUser({ email: faker.internet.email() });
  319. await adminPage.goto(`/admin/users/${user.id}`);
  320. await adminPage.click('[data-testid="assign-permissions"]');
  321. await adminPage.check('[data-testid="permission-read"]');
  322. await adminPage.check('[data-testid="permission-write"]');
  323. await adminPage.click('[data-testid="save-permissions"]');
  324. await expect(adminPage.getByText('Permissions updated')).toBeVisible();
  325. // Verify permissions assigned
  326. const response = await adminPage.request.get(`/api/users/${user.id}`);
  327. const updated = await response.json();
  328. expect(updated.permissions).toContain('read');
  329. expect(updated.permissions).toContain('write');
  330. });
  331. // Test 3: Notification preferences (70 lines)
  332. test('admin can update notification preferences', async ({ adminPage, seedUser }) => {
  333. const user = await seedUser({ email: faker.internet.email() });
  334. await adminPage.goto(`/admin/users/${user.id}/notifications`);
  335. await adminPage.check('[data-testid="email-notifications"]');
  336. await adminPage.uncheck('[data-testid="sms-notifications"]');
  337. await adminPage.selectOption('[data-testid="frequency"]', 'daily');
  338. await adminPage.click('[data-testid="save-preferences"]');
  339. await expect(adminPage.getByText('Preferences saved')).toBeVisible();
  340. // Verify preferences
  341. const response = await adminPage.request.get(`/api/users/${user.id}/preferences`);
  342. const prefs = await response.json();
  343. expect(prefs.emailEnabled).toBe(true);
  344. expect(prefs.smsEnabled).toBe(false);
  345. expect(prefs.frequency).toBe('daily');
  346. });
  347. // TOTAL: 3 tests × 60 lines avg = 180 lines
  348. // Each test is focused, debuggable, and under 300 lines
  349. ```
  350. **Key Points**:
  351. - Split monolithic tests into focused scenarios (<300 lines each)
  352. - Extract common setup into fixtures (auto-runs for each test)
  353. - Each test validates one concern (user creation, permissions, preferences)
  354. - Failures are easier to diagnose: "Permission assignment failed" vs "Complete journey failed"
  355. - Tests can run in parallel (isolated concerns)
  356. ### Example 5: Execution Time Optimization
  357. **Context**: When tests take longer than 1.5 minutes, they slow CI pipelines and feedback loops. Optimize by using API setup instead of UI navigation, parallelizing independent operations, and avoiding unnecessary waits.
  358. **Implementation**:
  359. ```typescript
  360. // ❌ BAD: 4-minute test (slow setup, sequential operations)
  361. test('user completes order - SLOW (4 min)', async ({ page }) => {
  362. // Step 1: Manual signup via UI (90 seconds)
  363. await page.goto('/signup');
  364. await page.fill('[data-testid="email"]', 'buyer@example.com');
  365. await page.fill('[data-testid="password"]', 'password123');
  366. await page.fill('[data-testid="confirm-password"]', 'password123');
  367. await page.fill('[data-testid="name"]', 'Buyer User');
  368. await page.click('[data-testid="signup"]');
  369. await page.waitForURL('/verify-email'); // Wait for email verification
  370. // ... manual email verification flow
  371. // Step 2: Manual product creation via UI (60 seconds)
  372. await page.goto('/admin/products');
  373. await page.fill('[data-testid="product-name"]', 'Widget');
  374. // ... 20 more fields
  375. await page.click('[data-testid="create-product"]');
  376. // Step 3: Navigate to checkout (30 seconds)
  377. await page.goto('/products');
  378. await page.waitForTimeout(5000); // Unnecessary hard wait
  379. await page.click('[data-testid="product-widget"]');
  380. await page.waitForTimeout(3000); // Unnecessary
  381. await page.click('[data-testid="add-to-cart"]');
  382. await page.waitForTimeout(2000); // Unnecessary
  383. // Step 4: Complete checkout (40 seconds)
  384. await page.goto('/checkout');
  385. await page.waitForTimeout(5000); // Unnecessary
  386. await page.fill('[data-testid="credit-card"]', '4111111111111111');
  387. // ... more form filling
  388. await page.click('[data-testid="submit-order"]');
  389. await page.waitForTimeout(10000); // Unnecessary
  390. await expect(page.getByText('Order Confirmed')).toBeVisible();
  391. // TOTAL: ~240 seconds (4 minutes)
  392. });
  393. // ✅ GOOD: 45-second test (API setup, parallel ops, deterministic waits)
  394. test('user completes order', async ({ page, apiRequest }) => {
  395. // Step 1: API setup (parallel, 5 seconds total)
  396. const [user, product] = await Promise.all([
  397. // Create user via API (fast)
  398. apiRequest
  399. .post('/api/users', {
  400. data: createUser({
  401. email: 'buyer@example.com',
  402. emailVerified: true, // Skip verification
  403. }),
  404. })
  405. .then((r) => r.json()),
  406. // Create product via API (fast)
  407. apiRequest
  408. .post('/api/products', {
  409. data: createProduct({
  410. name: 'Widget',
  411. price: 29.99,
  412. stock: 10,
  413. }),
  414. })
  415. .then((r) => r.json()),
  416. ]);
  417. // Step 2: Auth setup via storage state (instant, 0 seconds)
  418. await page.context().addCookies([
  419. {
  420. name: 'auth_token',
  421. value: user.token,
  422. domain: 'localhost',
  423. path: '/',
  424. },
  425. ]);
  426. // Step 3: Network-first interception BEFORE navigation (10 seconds)
  427. const cartPromise = page.waitForResponse('**/api/cart');
  428. const orderPromise = page.waitForResponse('**/api/orders');
  429. await page.goto(`/products/${product.id}`);
  430. await page.click('[data-testid="add-to-cart"]');
  431. await cartPromise; // Deterministic wait (no hard wait)
  432. // Step 4: Checkout with network waits (30 seconds)
  433. await page.goto('/checkout');
  434. await page.fill('[data-testid="credit-card"]', '4111111111111111');
  435. await page.fill('[data-testid="cvv"]', '123');
  436. await page.fill('[data-testid="expiry"]', '12/25');
  437. await page.click('[data-testid="submit-order"]');
  438. await orderPromise; // Deterministic wait (no hard wait)
  439. await expect(page.getByText('Order Confirmed')).toBeVisible();
  440. await expect(page.getByText(`Order #${product.id}`)).toBeVisible();
  441. // TOTAL: ~45 seconds (6x faster)
  442. });
  443. // Cypress equivalent
  444. describe('Order Flow', () => {
  445. it('should complete purchase quickly', () => {
  446. // Step 1: API setup (parallel, fast)
  447. const user = createUser({ emailVerified: true });
  448. const product = createProduct({ name: 'Widget', price: 29.99 });
  449. cy.task('db:seed', { users: [user], products: [product] });
  450. // Step 2: Auth setup via session (instant)
  451. cy.setCookie('auth_token', user.token);
  452. // Step 3: Network-first interception
  453. cy.intercept('POST', '**/api/cart').as('addToCart');
  454. cy.intercept('POST', '**/api/orders').as('createOrder');
  455. cy.visit(`/products/${product.id}`);
  456. cy.get('[data-cy="add-to-cart"]').click();
  457. cy.wait('@addToCart'); // Deterministic wait
  458. // Step 4: Checkout
  459. cy.visit('/checkout');
  460. cy.get('[data-cy="credit-card"]').type('4111111111111111');
  461. cy.get('[data-cy="cvv"]').type('123');
  462. cy.get('[data-cy="expiry"]').type('12/25');
  463. cy.get('[data-cy="submit-order"]').click();
  464. cy.wait('@createOrder'); // Deterministic wait
  465. cy.contains('Order Confirmed').should('be.visible');
  466. cy.contains(`Order #${product.id}`).should('be.visible');
  467. });
  468. });
  469. // Additional optimization: Shared auth state (0 seconds per test)
  470. // playwright/support/global-setup.ts
  471. export default async function globalSetup() {
  472. const browser = await chromium.launch();
  473. const page = await browser.newPage();
  474. // Create admin user once for all tests
  475. const admin = createUser({ role: 'admin', emailVerified: true });
  476. await page.request.post('/api/users', { data: admin });
  477. // Login once, save session
  478. await page.goto('/login');
  479. await page.fill('[data-testid="email"]', admin.email);
  480. await page.fill('[data-testid="password"]', 'password123');
  481. await page.click('[data-testid="login"]');
  482. // Save auth state for reuse
  483. await page.context().storageState({ path: 'playwright/.auth/admin.json' });
  484. await browser.close();
  485. }
  486. // Use shared auth in tests (instant)
  487. test.use({ storageState: 'playwright/.auth/admin.json' });
  488. test('admin action', async ({ page }) => {
  489. // Already logged in - no auth overhead (0 seconds)
  490. await page.goto('/admin');
  491. // ... test logic
  492. });
  493. ```
  494. **Key Points**:
  495. - Use API for data setup (10-50x faster than UI)
  496. - Run independent operations in parallel (`Promise.all`)
  497. - Replace hard waits with deterministic waits (`waitForResponse`)
  498. - Reuse auth sessions via `storageState` (Playwright) or `setCookie` (Cypress)
  499. - Skip unnecessary flows (email verification, multi-step signups)
  500. ## Integration Points
  501. - **Used in workflows**: `*atdd` (test generation quality), `*automate` (test expansion quality), `*test-review` (quality validation)
  502. - **Related fragments**:
  503. - `network-first.md` - Deterministic waiting strategies
  504. - `data-factories.md` - Isolated, parallel-safe data patterns
  505. - `fixture-architecture.md` - Setup extraction and cleanup
  506. - `test-levels-framework.md` - Choosing appropriate test granularity for speed
  507. ## Core Quality Checklist
  508. Every test must pass these criteria:
  509. - [ ] **No Hard Waits** - Use `waitForResponse`, `waitForLoadState`, or element state (not `waitForTimeout`)
  510. - [ ] **No Conditionals** - Tests execute the same path every time (no if/else, try/catch for flow control)
  511. - [ ] **< 300 Lines** - Keep tests focused; split large tests or extract setup to fixtures
  512. - [ ] **< 1.5 Minutes** - Optimize with API setup, parallel operations, and shared auth
  513. - [ ] **Self-Cleaning** - Use fixtures with auto-cleanup or explicit `afterEach()` teardown
  514. - [ ] **Explicit Assertions** - Keep `expect()` calls in test bodies, not hidden in helpers
  515. - [ ] **Unique Data** - Use `faker` for dynamic data; never hardcode IDs or emails
  516. - [ ] **Parallel-Safe** - Tests don't share state; run successfully with `--workers=4`
  517. _Source: Murat quality checklist, Definition of Done requirements (lines 370-381, 406-422)._