Laravel feature and unit tests, with a real app · Part 6 of 6

Testing7 min read

Browser tests with Pest and Playwright

Pest's browser plugin driving Chromium through the login and the invoice form's JavaScript, screenshots and traces of failures, a smoke test for script errors and accessibility, and the browser job in GitHub Actions.

By Abhishek Fouzdar · Updated

This part opens a real browser. Pest's browser plugin drives Chromium through Playwright, and the tests look like the feature tests of part 3 until they click a button that only JavaScript can handle. It ends with five browser tests, 128 tests in all, and a fifth CI job that runs them in GitHub Actions. Part 5 built the workflow; the series introduction explains InvoiceMini.

When a browser test is worth it

A feature test posts a form; a browser test fills it in. Everything a feature test can check, a browser test can check more slowly and with more ways to break, so the question is what a feature test cannot check. In InvoiceMini that is one thing: the invoice form's "Add line" and remove buttons, which are twenty lines of JavaScript that clone a row and re-index the field names. If that script is wrong, every feature test still passes, because they post the array directly, and every user is stuck at one line.

So the browser suite is small and specific: the login form (because a login that works in a test request and not in a browser is a thing that happens), the invoice form with its script, the validation errors as a user sees them, and one smoke test across the main pages for script errors and accessibility. Five tests, five seconds.

Install

composer require pestphp/pest-plugin-browser --dev
npm install --save-dev playwright
npx playwright install chromium
Chrome Headless Shell 156.0.8078.4 (playwright chromium-headless-shell v1248) downloaded to ~/.cache/ms-playwright/chromium_headless_shell-1248

A 120 MB download, about 270 MB on disk, once. The plugin starts Playwright's server from node_modules when the first browser test runs and stops it at the end.

Three configuration changes. tests/Pest.php binds the new folder to the Laravel test case too, and gives it back the Vite assets that part 5 took away from feature tests:

pest()->extend(TestCase::class)
    ->use(RefreshDatabase::class)
    ->in('Feature', 'Browser');

// Browser tests drive the real page, so they need the built assets that feature tests skip.
pest()->beforeEach(fn () => $this->withVite())->in('Browser');

phpunit.xml gets a third <testsuite name="Browser"> so ./vendor/bin/pest runs it by default, and .gitignore gets tests/Browser/Screenshots and tests/Browser/Traces, which the plugin fills when a test fails. Run npm run build before the first test; the pages load the real app.js.

The same application, a real page

The plugin serves the application from the test's own process. That sentence is the reason browser tests are cheap to write here: RefreshDatabase still resets the database, factories create what the page will show, actingAs() logs the browser in, and a Bus::fake() in the test is in effect when the page's request arrives.

beforeEach(function () {
    $this->company = Company::factory()->create(['name' => 'Acme Studio', 'currency' => 'EUR', 'default_tax_rate' => 20]);
    $this->user = User::factory()->for($this->company)->create(['email' => '[email protected]', 'password' => 'password']);
    $this->client = Client::factory()->for($this->company)->create(['name' => 'Northwind Traders']);
});

it('logs in through the form', function () {
    visit('/login')
        ->assertSee('Sign in to InvoiceMini')
        ->type('email', '[email protected]')
        ->type('password', 'password')
        ->press('Log in')
        ->assertPathIs('/invoices')
        ->assertSee('No invoices yet.');

    $this->assertAuthenticatedAs($this->user);
});

visit() opens the page and returns an object whose methods are the user's actions and the assertions on what they see. type() takes a field by name, id or CSS selector; press() takes a button's text; assertPathIs() waits, up to five seconds, for the browser to arrive there. The last line is a plain Laravel assertion on the guard, after the browser did the logging in. One test, both worlds.

The test that justifies the suite:

it('creates an invoice with a line added by the page script, then sends it', function () {
    Bus::fake(); // sending queues the PDF and mail; not the subject here
    $this->actingAs($this->user);

    $page = visit('/invoices/create')
        ->select('client_id', (string) $this->client->id)
        ->type('input[name="lines[0][description]"]', 'Design work')
        ->type('input[name="lines[0][quantity]"]', '2')
        ->type('input[name="lines[0][unit_price]"]', '50000')
        ->click('#add-line')                        // app.js clones the row and re-indexes the names
        ->assertCount('tr.line', 2)
        ->type('input[name="lines[1][description]"]', 'Hosting')
        ->type('input[name="lines[1][unit_price]"]', '2000')
        ->screenshot(fullPage: false, filename: 'invoice-form')
        ->press('Create draft')
        ->assertSee('Invoice created.');

    $invoice = Invoice::sole();

    $page->assertPathIs("/invoices/{$invoice->id}")
        ->assertSeeIn('[data-subtotal]', '€1,020.00')
        ->assertSeeIn('[data-total]', '€1,224.00')
        ->screenshot(fullPage: false, filename: 'invoice-draft')
        ->press('Send')
        ->assertSee('Invoice INV-2026-0001 sent.')
        ->assertSeeIn('[data-status]', 'Sent')
        ->screenshot(fullPage: false, filename: 'invoice-sent');

    expect($invoice->refresh())->number->toBe('INV-2026-0001')->lines->toHaveCount(2);
    Bus::assertDispatched(DeliverInvoice::class);
});
The invoice form in Chromium, with the second line added by the page's script, as the test saw it

click('#add-line') runs the script; assertCount('tr.line', 2) proves the row appeared; typing into lines[1][...] proves the re-indexing, because the cloned row started with the first row's names. assertSeeIn() scopes an assertion to a selector, and the data- attributes on the totals exist for exactly this: a test that reads [data-total] survives a redesign that a test reading the fifth table cell would not. After "Send", the page shows the number the server assigned, and the last two lines check the database and the job fake, as any feature test would.

A third test adds a line and removes it, and asserts the server never saw it. A fourth submits the empty form and asserts the errors are on the page, which is a different claim from part 3's "the session has errors": it is the user's view. The fifth is the one to copy into any project:

it('renders the main pages without script errors or serious accessibility issues', function () {
    $this->actingAs($this->user);
    $invoice = Invoice::factory()->recycle($this->company)->withLines(2)->sent()->create();

    visit(['/invoices', "/invoices/{$invoice->id}", '/invoices/create'])
        ->assertNoSmoke()
        ->assertNoAccessibilityIssues();
});

visit() with an array opens several pages, and the two assertions run on each. assertNoSmoke() is "no console output of any kind and no JavaScript errors"; assertNoAccessibilityIssues() runs an axe audit and fails on serious findings, missing labels, missing alt text, contrast. Both found nothing here because the pages are plain; on a page with a third-party widget, the first thing the smoke test finds is usually that widget.

Run it

./vendor/bin/pest tests/Browser
   PASS  Tests\Browser\InvoiceFlowTest
  ✓ it logs in through the form                                          0.77s
  ✓ it creates an invoice with a line added by the page script, then se… 1.17s
  ✓ it removes a line in the browser and the server never sees it        0.92s
  ✓ it shows validation errors next to the form, not a blank page        0.65s
  ✓ it renders the main pages without script errors or serious accessib… 0.90s

  Tests:    5 passed (34 assertions)
  Duration: 5.10s

A second per test, most of it the browser. The whole suite is now 128 tests in 11.8 seconds serially. The browser suite should run serially: --parallel on it hit a race in the plugin's server bookkeeping on this machine (below), and at five seconds there is nothing to gain.

When a browser test fails, the plugin saves a screenshot of the page at the moment of failure under tests/Browser/Screenshots, named after the test, and says so in the failure message. That is the first thing to open. --trace records a Playwright trace of each failed test, a timeline with DOM snapshots that opens at trace.playwright.dev; --debug runs headed and pauses on failure so you can look at the real window.

In CI

The browser job installs Node and Playwright's Chromium with its system dependencies, builds the assets, and uploads the screenshots and traces when something fails:

browser:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v5
    - uses: shivammathur/setup-php@v2
      with:
        php-version: '8.5'
        extensions: intl, sqlite3, pdo_sqlite, gd
        coverage: none
    - uses: actions/setup-node@v4
      with: { node-version: lts/*, cache: npm }
    - run: composer install --no-interaction --no-progress --prefer-dist
    - run: npm ci && npm run build
    - run: npx playwright install --with-deps chromium
    - run: cp .env.example .env && php artisan key:generate
    - run: ./vendor/bin/pest tests/Browser --ci --trace --compact
    - name: Upload screenshots and traces of failed tests
      uses: actions/upload-artifact@v4
      if: failure()
      with:
        name: browser-tests
        path: |
          tests/Browser/Screenshots
          tests/Browser/Traces

--with-deps is what makes Chromium start on a bare runner; it installs the shared libraries with apt and is the reason the job needs sudo, which GitHub's runners have. The run:

browser: success  08:26:51-08:27:29
  Tests:    5 passed (34 assertions)
  Duration: 3.47s

Thirty-eight seconds for the job, three and a half for the tests. The other four jobs were untouched by this part because part 5 scoped them to the unit and feature suites.

The sent invoice as the browser test left it: number assigned, status Sent, totals the server computed

The part 6 commit has the tests, the configuration, the workflow job and the README.

What went wrong

Actual path [/login] does not equal expected path [/invoices] after press('Log in'), with the saved screenshot showing a filled-in form that nobody had submitted. The page's heading was also "Log in", and the press matched it. The heading is now "Sign in to InvoiceMini". When a press does nothing, check what else on the page has that text.

Timeout 5000ms exceeded on press('+ Add line'). The plugin could not resolve the button from that text, whether because of the plus sign or the leading space I never found out; click('#add-line') by id is unambiguous and does not depend on the label. Give the controls your tests use an id or a data- attribute.

screenshot(): Argument #1 ($fullPage) must be of type bool, string given. The method is screenshot(bool $fullPage = true, ?string $filename = null); named arguments make it readable and safe.

The next run hangs for minutes, with no output. An interrupted run leaves playwright run-server processes behind, and the next run waits on them. pkill -f "playwright run-serve[r]" clears them; the bracket keeps pkill from matching itself. Check with pgrep -fa playwright before assuming the tests are slow.

file_get_contents(.../pest-plugin-browser/.temp/playwright-server.json): No such file or directory under --parallel, in one of eight processes, not always the same one. The workers share one file that records where the Playwright server is, and one of them removes it while another still needs it. Plugin 5.1.2, Pest 5.3.3. Run the browser suite serially; it is five seconds.

Where this leaves you

The series started with two words and ends with 128 tests in six files' worth of ideas. If one thing travels to your own project, make it the rule from part 2: keep the arithmetic in classes that know nothing about Laravel, test those with plain PHP, and let the feature tests prove the plumbing. Everything else, the fakes, the clock, the factories, the workflow, is there to make that cheap enough to keep doing.

The repository is shipbytes/laravel-testing-guide, one commit per part. Questions and corrections go in its issues, or in the comments below.

New posts by email

Get new posts by email. Nothing else, no digests, unsubscribe in one click.

Comments

Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.