Stop crying at 2am during E2E tests: How to automate your defense with Playwright

Stop crying at 2am during E2E tests: How to automate your defense with Playwright

Have you ever felt hopeless at 2am during an E2E test? I am.
That night, right before the release, we were hit with a fatal bug that ``the payment button couldn't be pressed,'' and in the end, we had to manually click all the screens in the production environment, trembling. I'm sorry about that again.

The technical articles on the market, such as ``Philosophy of Test Design'' and ``The Ultimate Page Object Model,'' list so many complicated things that it makes me feel nauseous. There is no need for such a heavy design in the field of personal development or startups.
The essence of Playwright is to ``translate the actions that humans use when using a browser into code''. That's all.


1. Throw away all complicated settings

First, take a look at the basic test code. That's enough.

// tests/login.spec.js
import { test, expect } from '@playwright/test';

test('Can you log in and see the dashboard?', async ({ page }) => {
  await page.goto('/login');
  // Use data-testid instead of CSS class for selector. This is the only way to prevent the tragedy of tests dying due to design changes.
  await page.getByTestId('email-input').fill('[email protected]');
  await page.getByTestId('password-input').fill('password123');
  await page.getByRole('button', { name: 'Login' }).click();

  await expect(page).toHaveURL(/.*dashboard/);
  await expect(page.getByRole('heading')).toHaveText('Welcome back');
});
`

Anyone who wonders, "What's the standby time? What about `sleep'?" is under the spell of Selenium. Playwright's auto-waiting is so good that if you write an explicit `sleep`, you'll lose. It will automatically wait until the element is displayed.これを知った時、俺は思わず「マジかよ」と声が出た。


2. 泥臭い壁:認証(ログイン状態)の保持

It's nonsense to write a login process every time you test.テストが10個あれば10回ログインするのか? Too wasteful.
The most addictive part of the job is managing authentication information. `storageState`を使えば、ログイン後のセッションをファイルに保存し、それを使い回せる。

// playwright.config.js
module.exports = {
  use: {
    // Save and reuse the login state to speed up the process
    storageState: 'state.json',
  },
};
`

Now you can start testing right from the dashboard without having to go through the login screen each time.これが「実戦」の知恵だ。


3. GitHub Actions:CIのスペックはケチるな

ローカルでは動くのにGitHub Actionsでだけ落ちる。この現象に3日間溶かした俺の教訓を教える。原因の9割は「画面サイズ」と「リソース不足」だ。

`

# .github/workflows/e2e.yml
name: Playwright Tests
on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      -run: npm ci
      -run: npx playwright install --with-deps
      -run: npx playwright test
      - uses: actions/upload-artifact@v4
        if: always() # テストが落ちてもレポートを確実に残す
        with:
name: playwright-report
          path: playwright-report/
`

`actions/checkout@v4` を使え。古いバージョンはもう捨てろ。 And if you force it to run on a low-memory instance, the browser will randomly crash and go crazy. The execution time of CI is "the lifespan of the developer". Don't be stingy.


4. 拡張性との付き合い方

“When should I introduce Page Object Model (POM)?”
The answer is simple. "When copying and pasting the test code occurs 3 times".
最初はベタ書きでいい。 It is enough to think about building a complex framework after you have over 1000 tests. The first step is to build up the fact that it works.


5. E2E testing = investing in business value

"I want to implement new features when I have time to write tests."その気持ちは痛いほどわかる。 But you never want to experience the cold sweat of hitting the deploy button and finding out your payment functionality is dead.

E2E testing is not about perfection. This is insurance to ensure that only critical flow lines will never die.

Automated testing eliminates psychological barriers to deployment.
The sense of security that ``Even if something breaks, CI will tell you what to do'' dramatically accelerates development speed. Merge code with confidence and release with confidence. That's why we write tests.

After all, E2E tests aren't about "writing." The correct answer is to let the browser do the work for us and do more important work.

Now, hit `npx playwright codegen` to automatically generate your first test. Bringing back your night begins with that one group right now.


🤖 Developer blog/public content

The developer's personal blog is also available, so please take a look. 👉 muttyan.com (Developer Blog)