| title | Browser Testing |
|---|---|
| description | Browser testing lets you drive a real browser to ensure your application works correctly across different browsers and devices, all with Pest's simple and elegant syntax. |
Browser testing is an essential part of modern web development, allowing you to ensure that your application works correctly across different browsers and devices. Pest provides a simple and elegant way to write browser tests. Here is an example of how to write a browser test using Pest:
it('may welcome the user', function () {
$page = visit('/');
$page->assertSee('Welcome');
});This is a basic example of a browser test that checks whether the homepage contains the text "Welcome". However, Pest's browser testing capabilities go well beyond this simple example. You may use various methods to interact with the page, such as clicking buttons, filling out forms, and navigating between pages.
Here is an example of a more complex browser test, written in a Laravel application, that checks whether a user can sign in:
it('may sign in the user', function () {
Event::fake();
User::factory()->create([ // assumes RefreshDatabase trait is used on Pest.php...
'email' => 'nuno@laravel.com',
'password' => 'password',
]);
$page = visit('/')->on()->mobile()->firefox();
$page->click('Sign In')
->assertUrlIs('/login')
->assertSee('Sign In to Your Account')
->fill('email', 'nuno@laravel.com')
->fill('password', 'password')
->click('Submit')
->assertSee('Dashboard');
$this->assertAuthenticated();
Event::assertDispatched(UserLoggedIn::class);
});As you can see, you may leverage the full power of Laravel's testing capabilities — database refreshing, event faking, and authentication assertions — while also performing real browser testing.
To get started with browser testing in Pest, require the Pest Browser plugin via Composer and install Playwright:
composer require pestphp/pest-plugin-browser --dev
npm install playwright@latest
npx playwright installFinally, you should add tests/Browser/Screenshots to your .gitignore file to avoid committing screenshots taken during browser tests.
Running browser tests is similar to running regular Pest tests:
./vendor/bin/pestWe recommend running tests in parallel using the --parallel option to speed up the execution:
./vendor/bin/pest --parallelFor debugging purposes, you may run the tests in a headed mode and pause the execution at the end of the failed test run:
./vendor/bin/pest --debugThe visit() method is used to navigate to a specific URL in your browser test. It provides various methods to interact with the page:
test('example', function () {
$page = visit('/');
$page->assertSee('Welcome');
});By default, the visit() method uses Chrome as the browser. However, if you wish to use a different browser, you may specify it using the --browser option when running your tests:
./vendor/bin/pest --browser firefox
./vendor/bin/pest --browser safariIf you wish to use a different browser by default without specifying it on the command line, you may set it in your Pest.php configuration file:
pest()->browser()->inFirefox();
pest()->browser()->inSafari();By default, the visit() method uses a desktop viewport. However, you may specify a mobile viewport by chaining the mobile() method onto the on() method:
$page = visit('/')->on()->mobile();If you wish to use a specific device, you may use the on() method and chain it with a device method such as macbook14() or iPhone14Pro():
$page = visit('/')->on()->iPhone14Pro();By default, Pest enforces a light color scheme. However, you may specify a dark color scheme using the inDarkMode() method:
$page = visit('/')->inDarkMode();You may visit multiple pages simultaneously by passing an array of URLs to the visit() method. This is convenient for testing scenarios where you need to interact with multiple pages at once:
$pages = visit(['/', '/about']);
$pages->assertNoSmoke()
->assertNoAccessibilityIssues()
->assertNoConsoleLogs()
->assertNoJavaScriptErrors();
[$homePage, $aboutPage] = $pages;
$homePage->assertSee('Welcome to our website');
$aboutPage->assertSee('About Us');After visiting a page, you may navigate to other pages using the navigate() method. This method allows you to navigate to a different URL while keeping the current browser context:
$page = visit('/');
$page->navigate('/about')
->assertSee('About Us');You may locate elements in the DOM using text or CSS selectors. Pest provides a simple syntax for doing so:
// Clicks the first link with the text "Login"
$page->click('Login');
// Clicks the first element with the class "btn-primary"
$page->click('.btn-primary');
// Clicks the element with the data-test attribute "login"
$page->click('@login');
// Clicks the element with the ID "submit-button"
$page->click('#submit-button');
// etc...Sometimes elements may take time to appear on the page. By default, Pest waits 5 seconds before timing out. However, you may configure the default timeout for browser tests in your Pest.php configuration file:
pest()->browser()->timeout(10000);By default, the user agent matches the browser you are running your tests in, such as Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/133.0.6943.16 Safari/537.36.
Sometimes you may wish to override the browser's user agent for all of your tests. To accomplish this, you may configure it in your Pest.php configuration file:
pest()->browser()->userAgent('CustomUserAgent');By default, the server binds to 127.0.0.1 for all browser tests. However, you may wish to override the host when testing subdomain applications. To accomplish this, you may configure it in your Pest.php configuration file:
pest()->browser()->withHost('some-subdomain.localhost');Sometimes you may need to define where the browser believes it is physically located on the earth. To accomplish this, you may use the geolocation() method, which takes a latitude and longitude, sets the geolocation permission in the browser, and then makes the coordinates available via JavaScript's getCurrentPosition API:
$page = visit('/')
->geolocation(39.399872, -8.224454);
$page->assertSee('Portugal');You may also define one of several specific preset cities, which will configure the browser's geolocation, timezone, and locale:
$page = visit('/')
->from()->losAngeles();
$page->assertSee('Los Angeles');
$page->assertSee('America/Los_Angeles');
$page->assertSee('en-US');You may set the locale for your test requests using the withLocale method. This is particularly convenient for testing multilingual applications:
$page = visit('/')->withLocale('fr-FR');
$page->assertSee('Bienvenue');You may set the timezone for your test requests using the withTimezone method. This is helpful for testing date and time displays across different time zones:
$page = visit('/')->withTimezone('America/New_York');
$page->assertSee('EST');You may set the User-Agent header for your test requests using the withUserAgent method. This is helpful for testing how your application responds to different types of clients, such as mobile browsers or bots:
$page = visit('/')->withUserAgent('Googlebot');
$page->assertSee('Welcome, bot!');You may set the host for your test server using the withHost method. This is helpful for testing subdomains, or where different hosts serve different content:
$page = visit('/dashboard')->withHost('some-subdomain.localhost');
$page->assertSee('Welcome to Some Subdomain');assertTitle assertTitleContains assertSee assertDontSee assertSeeIn assertDontSeeIn assertSeeAnythingIn assertSeeNothingIn assertCount assertScript assertSourceHas assertSourceMissing assertSeeLink assertDontSeeLink assertChecked assertNotChecked assertIndeterminate assertRadioSelected assertRadioNotSelected assertSelected assertNotSelected assertValue assertValueIsNot assertAttribute assertAttributeMissing assertAttributeContains assertAttributeDoesntContain assertAriaAttribute assertDataAttribute assertVisible assertPresent assertNotPresent assertMissing assertEnabled assertDisabled assertButtonEnabled assertButtonDisabled assertUrlIs assertSchemeIs assertSchemeIsNot assertHostIs assertHostIsNot assertPortIs assertPortIsNot assertPathBeginsWith assertPathEndsWith assertPathContains assertPathIs assertPathIsNot assertQueryStringHas assertQueryStringMissing assertFragmentIs assertFragmentBeginsWith assertFragmentIsNot assertNoSmoke assertNoConsoleLogs assertNoJavaScriptErrors assertNoAccessibilityIssues assertScreenshotMatches
click text attribute keys withKeyDown type typeSlowly select append clear radio check uncheck attach press pressAndWaitFor drag hover submit value withinFrame resize script content url wait waitForKey
The assertTitle method asserts that the page title matches the given text:
$page->assertTitle('Home Page');The assertTitleContains method asserts that the page title contains the given text:
$page->assertTitleContains('Home');The assertSee method asserts that the given text is present on the page:
$page->assertSee('Welcome to our website');The assertDontSee method asserts that the given text is not present on the page:
$page->assertDontSee('Error occurred');The assertSeeIn method asserts that the given text is present within the selector:
$page->assertSeeIn('.header', 'Welcome');The assertDontSeeIn method asserts that the given text is not present within the selector:
$page->assertDontSeeIn('.error-container', 'Error occurred');The assertSeeAnythingIn method asserts that any text is present within the selector:
$page->assertSeeAnythingIn('.content');The assertSeeNothingIn method asserts that no text is present within the selector:
$page->assertSeeNothingIn('.empty-container');The assertCount method asserts that a given element is present a given number of times:
$page->assertCount('.item', 5);The assertScript method asserts that the given JavaScript expression evaluates to the given value:
$page->assertScript('document.title', 'Home Page');
$page->assertScript('document.querySelector(".btn").disabled', true);The assertSourceHas method asserts that the given source code is present on the page:
$page->assertSourceHas('<h1>Welcome</h1>');The assertSourceMissing method asserts that the given source code is not present on the page:
$page->assertSourceMissing('<div class="error">');The assertSeeLink method asserts that the given link is present on the page:
$page->assertSeeLink('About Us');The assertDontSeeLink method asserts that the given link is not present on the page:
$page->assertDontSeeLink('Admin Panel');The assertChecked method asserts that the given checkbox is checked:
$page->assertChecked('terms');
$page->assertChecked('color', 'blue'); // For checkbox with specific valueThe assertNotChecked method asserts that the given checkbox is not checked:
$page->assertNotChecked('newsletter');
$page->assertNotChecked('color', 'red'); // For checkbox with specific valueThe assertIndeterminate method asserts that the given checkbox is in an indeterminate state:
$page->assertIndeterminate('partial-selection');The assertRadioSelected method asserts that the given radio field is selected:
$page->assertRadioSelected('size', 'large');The assertRadioNotSelected method asserts that the given radio field is not selected:
$page->assertRadioNotSelected('size', 'small');The assertSelected method asserts that the given dropdown has the given value selected:
$page->assertSelected('country', 'US');The assertNotSelected method asserts that the given dropdown does not have the given value selected:
$page->assertNotSelected('country', 'UK');The assertValue method asserts that the element matching the given selector has the given value:
$page->assertValue('input[name=email]', 'test@example.com');The assertValueIsNot method asserts that the element matching the given selector does not have the given value:
$page->assertValueIsNot('input[name=email]', 'invalid@example.com');The assertAttribute method asserts that the element matching the given selector has the given value in the provided attribute:
$page->assertAttribute('img', 'alt', 'Profile Picture');The assertAttributeMissing method asserts that the element matching the given selector is missing the provided attribute:
$page->assertAttributeMissing('button', 'disabled');The assertAttributeContains method asserts that the element matching the given selector contains the given value in the provided attribute:
$page->assertAttributeContains('div', 'class', 'container');The assertAttributeDoesntContain method asserts that the element matching the given selector does not contain the given value in the provided attribute:
$page->assertAttributeDoesntContain('div', 'class', 'hidden');The assertAriaAttribute method asserts that the element matching the given selector has the given value in the provided aria attribute:
$page->assertAriaAttribute('button', 'label', 'Close');The assertDataAttribute method asserts that the element matching the given selector has the given value in the provided data attribute:
$page->assertDataAttribute('div', 'id', '123');The assertVisible method asserts that the element matching the given selector is visible:
$page->assertVisible('.alert');The assertPresent method asserts that the element matching the given selector is present in the DOM:
$page->assertPresent('form');The assertNotPresent method asserts that the element matching the given selector is not present in the DOM:
$page->assertNotPresent('.error-message');The assertMissing method asserts that the element matching the given selector is not visible:
$page->assertMissing('.hidden-element');The assertEnabled method asserts that the given field is enabled:
$page->assertEnabled('email');The assertDisabled method asserts that the given field is disabled:
$page->assertDisabled('submit');The assertButtonEnabled method asserts that the given button is enabled:
$page->assertButtonEnabled('Save');The assertButtonDisabled method asserts that the given button is disabled:
$page->assertButtonDisabled('Submit');The assertUrlIs method asserts that the current URL matches the given string:
$page->assertUrlIs('https://example.com/home');The assertSchemeIs method asserts that the current URL scheme matches the given scheme:
$page->assertSchemeIs('https');The assertSchemeIsNot method asserts that the current URL scheme does not match the given scheme:
$page->assertSchemeIsNot('http');The assertHostIs method asserts that the current URL host matches the given host:
$page->assertHostIs('example.com');The assertHostIsNot method asserts that the current URL host does not match the given host:
$page->assertHostIsNot('wrong-domain.com');The assertPortIs method asserts that the current URL port matches the given port:
$page->assertPortIs('443');The assertPortIsNot method asserts that the current URL port does not match the given port:
$page->assertPortIsNot('8080');The assertPathBeginsWith method asserts that the current URL path begins with the given path:
$page->assertPathBeginsWith('/users');The assertPathEndsWith method asserts that the current URL path ends with the given path:
$page->assertPathEndsWith('/profile');The assertPathContains method asserts that the current URL path contains the given path:
$page->assertPathContains('settings');The assertPathIs method asserts that the current path matches the given path:
$page->assertPathIs('/dashboard');The assertPathIsNot method asserts that the current path does not match the given path:
$page->assertPathIsNot('/login');The assertQueryStringHas method asserts that the given query string parameter is present and has a given value:
$page->assertQueryStringHas('page');
$page->assertQueryStringHas('page', '2');The assertQueryStringMissing method asserts that the given query string parameter is missing:
$page->assertQueryStringMissing('page');The assertFragmentIs method asserts that the URL's current hash fragment matches the given fragment:
$page->assertFragmentIs('section-2');The assertFragmentBeginsWith method asserts that the URL's current hash fragment begins with the given fragment:
$page->assertFragmentBeginsWith('section');The assertFragmentIsNot method asserts that the URL's current hash fragment does not match the given fragment:
$page->assertFragmentIsNot('wrong-section');The assertNoSmoke method asserts there are no console logs or JavaScript errors on the page:
$page->assertNoSmoke();The assertNoConsoleLogs method asserts there are no console logs on the page:
$page->assertNoConsoleLogs();The assertNoJavaScriptErrors method asserts there are no JavaScript errors on the page:
$page->assertNoJavaScriptErrors();The assertNoAccessibilityIssues method asserts there are no "serious" accessibility issues on the page:
$page->assertNoAccessibilityIssues();By default, the level is 1 (serious). However, you may change it to one of the following levels:
0. Critical
1. Serious
2. Moderate
3. Minor
- The level 0 (critical) only reports issues that cause severe barriers for individuals with disabilities. The organization may be subject to legal action if these issues are not addressed.
- The level 1 (serious) includes all critical issues (level 0) and adds issues that significantly impact accessibility. The organization may be subject to legal action if these issues are not addressed.
- The level 2 (moderate) includes all serious issues (level 1) and adds issues that moderately affect accessibility. The end-user would appreciate the fix, but it is not a barrier.
- The level 3 (minor) includes all moderate issues (level 2) and adds issues that have a minor impact on accessibility. These issues are often related to best practices and do not significantly affect the user experience.
The assertScreenshotMatches method asserts that the screenshot matches the expected image:
$page->assertScreenshotMatches();
$page->assertScreenshotMatches(true, true); // Full page, show diffThe click method clicks the link with the given text:
$page->click('Login');The text method gets the text of the element matching the given selector:
$text = $page->text('.header');The attribute method gets the given attribute from the element matching the given selector:
$alt = $page->attribute('img', 'alt');The keys method sends the given keys to the element matching the given selector:
$page->keys('input[name=password]', 'secret');
$page->keys('input[name=password]', ['{Control}', 'a']); // Keyboard shortcutsThe withKeyDown method executes the given callback while a key is held down:
$page->withKeyDown('Shift', function () use ($page): void {
$page->keys('#input', ['KeyA', 'KeyB', 'KeyC']);
}); // writes "ABC"Note: To respect held keys such as
Shift, use key codes likeKeyA,KeyB, andKeyC—'a'always types a lowercase "a" and'A'always types an uppercase "A", regardless of modifiers.
The type method types the given value in the given field:
$page->type('email', 'test@example.com');The typeSlowly method types the given value in the given field slowly, like a user:
$page->typeSlowly('email', 'test@example.com');The select method selects the given value in the given field:
$page->select('country', 'US');
$page->select('interests', ['music', 'sports']); // Multiple selectThe append method types the given value in the given field without clearing it:
$page->append('description', ' Additional information.');The clear method clears the given field:
$page->clear('search');The radio method selects the given value of a radio button field:
$page->radio('size', 'large');The check method checks the given checkbox:
$page->check('terms');
$page->check('color', 'blue'); // For checkbox with specific valueThe uncheck method unchecks the given checkbox:
$page->uncheck('newsletter');
$page->uncheck('color', 'red'); // For checkbox with specific valueThe attach method attaches the given file to the field:
$page->attach('avatar', '/path/to/image.jpg');The press method presses the button with the given text or name:
$page->press('Submit');The pressAndWaitFor method presses the button with the given text or name and waits for a specified amount of time:
$page->pressAndWaitFor('Submit', 2); // Wait for 2 secondsThe drag method drags an element to another element using selectors:
$page->drag('#item', '#target');The hover method hovers over the given element:
$page->hover('#item');The submit method submits the first form found on the page:
$page->submit();The value method gets the value of the element matching the given selector:
$value = $page->value('input[name=email]');The withinFrame method allows you to interact with elements inside an iframe:
use Pest\Browser\Api\AwaitableWebpage;
$page->withinFrame('.iframe-container', function (AwaitableWebpage $page) {
$page->type('frame-input', 'Hello iframe')
->click('frame-button');
});The resize method adjusts the size of the browser window:
$page->resize(1280, 720);The script method executes a script in the context of the page:
$result = $page->script('document.title');The content method gets the page's content:
$html = $page->content();The url method gets the page's URL:
$currentUrl = $page->url();The wait method pauses for the given number of seconds:
$page->wait(2); // Wait for 2 secondsThe waitForKey method opens the current page URL in the default web browser and waits for a key press:
$page->waitForKey(); // Useful for debugging
Sometimes you may wish to debug your browser tests. Pest provides a convenient way to do this through the --debug option, which opens the browser window and pauses the execution of the test when it fails. You may then inspect the page and see what went wrong:
./vendor/bin/pest --debugAlternatively, you may use the debug() method in your test. It will limit execution to this test (like using only()), pause the execution, and open the browser window:
$page->debug();
You may also take a screenshot of the current page using the screenshot() method, which is convenient for visual debugging:
$page->screenshot();
$page->screenshot(fullPage: true);
$page->screenshot(filename: 'custom-name');Note: If you do not pass a filename, the test name will be used as the filename.
You may also take a screenshot of a specific element using the screenshotElement() method:
$page->screenshotElement('#my-element');
You may also use the tinker() method to open a Tinker session in the context of the current page, allowing you to interact with the page using PHP code:
$page->tinker();
You may also run your tests with the --headed option to open the browser window:
./vendor/bin/pest --headedIf you wish to run the tests in a headed mode by default, you may set it in your Pest.php configuration file:
pest()->browser()->headed();You may refer to Pest's Continuous Integration documentation for more information on how to run your browser tests in a CI environment.
However, if you are using GitHub Actions, you should add the following steps to your workflow file:
- uses: actions/setup-node@v4
with:
node-version: lts/*
- name: Install dependencies
run: npm ci
- name: Install Playwright Browsers
run: npx playwright install --with-depsNow, let's look at how the Agent plugin gives your AI coding agents a single command to verify a change actually works — running inside your full test suite, and, with this plugin installed, driving a real browser too: Agent →