### Install zenstruck/browser via Composer Source: https://github.com/zenstruck/browser/blob/1.x/README.md Standard Composer command to install the zenstruck/browser library as a development dependency for your PHP project. ```bash composer require zenstruck/browser --dev ``` -------------------------------- ### HTTP Requests Source: https://github.com/zenstruck/browser/blob/1.x/README.md This section details how to make various HTTP requests (GET, PUT, POST, DELETE) using the KernelBrowser. It also explains how to pass request options such as headers, body, and JSON data, and how to simulate AJAX requests. ```APIDOC ## HTTP Requests ### Description Make various HTTP requests (GET, PUT, POST, DELETE) using the KernelBrowser and configure request options. ### Method GET, PUT, POST, DELETE ### Endpoint /api/endpoint ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **headers** (array) - Optional - Request headers. * **body** (string) - Optional - Request body. * **json** (array) - Optional - JSON encoded request body. * **ajax** (boolean) - Optional - Simulate an AJAX request. ### Request Example ```php post('/api/endpoint', [ 'headers' => ['X-Token' => 'my-token'], 'body' => 'request body', ]) ->post('/api/endpoint', [ 'json' => ['request' => 'body'], 'ajax' => true, ]) ->post('/api/endpoint', HttpOptions::create()->withHeader('X-Token', 'my-token')->withBody('request body') ) ->post('/api/endpoint', HttpOptions::json()) ->post('/api/endpoint', HttpOptions::json(['request' => 'body'])) ->post('/api/endpoint', HttpOptions::ajax()) ->post('/api/endpoint', HttpOptions::jsonAjax()) ; ``` ### Response #### Success Response (200) Details of the response depend on the endpoint. #### Response Example No specific example provided, depends on the endpoint. ``` -------------------------------- ### Zenstruck Browser Actions and Assertions Source: https://github.com/zenstruck/browser/blob/1.x/README.md Provides a comprehensive list of available methods for interacting with web pages and asserting their content. Includes actions like visiting, clicking, filling forms, and various assertions for checking text, elements, attributes, and form field states. This example showcases common browser operations. ```php /** @var \Zenstruck\Browser $browser **/ $browser // ACTIONS ->visit('/my/page') ->click('A link') ->fillField('Name', 'Kevin') ->checkField('Accept Terms') ->uncheckField('Accept Terms') ->selectField('Canada') // "radio" select ->selectField('Type', 'Employee') // "select" single option ->selectField('Notification', ['Email', 'SMS']) // "select" multiple options ->selectField('Notification', []) // "un-select" all multiple options ->attachFile('Photo', '/path/to/photo.jpg') ->attachFile('Photo', ['/path/to/photo1.jpg', '/path/to/photo2.jpg']) // attach multiple files (if field supports this) ->click('Submit') // ASSERTIONS ->assertOn('/my/page') // by default checks "path", "query" and "fragment" ->assertOn('/a/page', ['path']) // check just the "path" // these look in the entire response body (useful for non-html pages) ->assertContains('some text') ->assertNotContains('some text') // these look in the html only ->assertSee('some text') ->assertNotSee('some text') ->assertSeeIn('h1', 'some text') ->assertNotSeeIn('h1', 'some text') ->assertSeeElement('h1') ->assertNotSeeElement('h1') ->assertElementCount('ul li', 2) ->assertElementAttributeContains('head meta[name=description]', 'content', 'my description') ->assertElementAttributeNotContains('head meta[name=description]', 'content', 'my description') // form field assertions ->assertFieldEquals('Username', 'kevin') ->assertFieldNotEquals('Username', 'john') // form checkbox assertions ->assertChecked('Accept Terms') ->assertNotChecked('Accept Terms') // form select assertions ->assertSelected('Type', 'Employee') ->assertNotSelected('Type', 'Admin') // form multi-select assertions ->assertSelected('Roles', 'Content Editor') ->assertSelected('Roles', 'Human Resources') ->assertNotSelected('Roles', 'Owner') ; ``` -------------------------------- ### Make HTTP Requests with KernelBrowser Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates how to perform various HTTP requests (GET, PUT, POST, DELETE) using KernelBrowser. Supports passing request options like headers and body as arrays or HttpOptions objects. JSON payloads and AJAX requests can be easily simulated. ```php use Zenstruck\Browser\HttpOptions; /** @var \Zenstruck\Browser\KernelBrowser $browser **/ $browser // http methods ->get('/api/endpoint') ->put('/api/endpoint') ->post('/api/endpoint') ->delete('/api/endpoint') // second parameter can be an array of request options ->post('/api/endpoint', [ // request headers 'headers' => ['X-Token' => 'my-token'], // request body 'body' => 'request body', ]) ->post('/api/endpoint', [ // json_encode request body and set Content-Type/Accept headers to application/json 'json' => ['request' => 'body'], // simulates an AJAX request (sets the X-Requested-With to XMLHttpRequest) 'ajax' => true, ]) // optionally use the provided Zenstruck\Browser\HttpOptions object ->post('/api/endpoint', HttpOptions::create()->withHeader('X-Token', 'my-token')->withBody('request body') ) // sets the Content-Type/Accept headers to application/json ->post('/api/endpoint', HttpOptions::json()) // json encodes value and sets as body ->post('/api/endpoint', HttpOptions::json(['request' => 'body'])) // simulates an AJAX request (sets the X-Requested-With to XMLHttpRequest) ->post('/api/endpoint', HttpOptions::ajax()) // simulates a JSON AJAX request ->post('/api/endpoint', HttpOptions::jsonAjax()) ; ``` -------------------------------- ### Configure Default Browser Options in Tests (PHP) Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates how to override the `xBrowser()` method in a test class to set default browser options and starting states. This allows for consistent browser setup across multiple tests. It utilizes the `HasBrowser` trait and `KernelBrowser` from Symfony and Zenstruck Browser. ```php namespace App\Tests; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Zenstruck\Browser\KernelBrowser; use Zenstruck\Browser\Test\HasBrowser; class MyTest extends KernelTestCase { use HasBrowser { browser as baseKernelBrowser; } public function testDemo(): void { $this->browser() ->assertOn('/') // browser always starts on the homepage (as defined below) ; } protected function browser(): KernelBrowser { return $this->baseKernelBrowser() ->interceptRedirects() // always intercept redirects ->throwExceptions() // always throw exceptions ->visit('/') // always start on the homepage ; } } ``` -------------------------------- ### Create and Use a Custom Comment Component (PHP) Source: https://github.com/zenstruck/browser/blob/1.x/README.md Provides a detailed example of creating a custom `CommentComponent` that extends `Zenstruck\Browser\Component`. This component includes assertions and actions for commenting on a page. It demonstrates how to define pre-assertions and pre-actions, and how to use the component in tests. ```php namespace App\Tests; use Zenstruck\Browser\Component; use Zenstruck\Browser\KernelBrowser; /** * If only using this component with a specific browser, this type hint can help your IDE. * * @method KernelBrowser browser() **/ class CommentComponent extends Component { public function assertHasNoComments(): self { $this->browser()->assertElementCount('#comments li', 0); return $this; // optionally make methods fluent } public function assertHasComment(string $body, string $author): self { $this->browser() ->assertSeeIn('#comments li span.body', $body) ->assertSeeIn('#comments li span.author', $author) ; return $this; // optionally make methods fluent } public function addComment(string $body, string $author): self { $this->browser() ->fillField('Name', $author) ->fillField('Comment', $body) ->click('Add Comment') ; return $this; // optionally make methods fluent } protected function preAssertions(): void { // this is called as soon as the component is loaded $this->browser()->assertSeeElement('#comments'); } protected function preActions(): void { // this is called when the component is loaded but before // preAssertions(). Useful for page components where you // need to navigate to the page: // $this->browser()->visit('/contact'); } } ``` ```php /** @var \Zenstruck\Browser $browser **/ $browser ->visit('/post/1') ->use(function(CommentComponent $component) { // the function typehint triggers the component to be loaded, // preActions() run and preAssertions() run $component ->assertHasNoComments() ->addComment('comment body', 'Kevin') ->assertHasComment('comment body') ; }) ; // you can optionally inject multiple components into the ->use() callback $browser->use(function(Component1 $component1, Component2 $component2) { $component1->doSomething(); $component2->doSomethingElse(); }); ``` -------------------------------- ### Using Components with Zenstruck Browser (PHP) Source: https://github.com/zenstruck/browser/blob/1.x/README.md Shows how to inject and use custom components within the Zenstruck Browser. Components encapsulate reusable testing logic and can be accessed via the `->use()` method. This example demonstrates injecting a `MyComponent` and calling its methods. ```php /** @var \Zenstruck\Browser $browser **/ $browser ->use(function(MyComponent $component) { $component->method(); }) ; ``` -------------------------------- ### Base Functional Test Case with Custom Browser Source: https://github.com/zenstruck/browser/blob/1.x/README.md Provides an example of a base functional test case that uses the @method annotation to enable autocompletion for custom browser methods, ensuring a better developer experience when using custom browser classes. ```php namespace App\Tests; use App\Tests\AppBrowser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Zenstruck\Browser\Test\HasBrowser; /** * @method AppBrowser browser() **/ abstract class MyTest extends WebTestCase { use HasBrowser; } ``` -------------------------------- ### PHP Test Using Custom Authentication Extension Source: https://github.com/zenstruck/browser/blob/1.x/README.md This PHP test method demonstrates how to use the custom `AppBrowser` class and its integrated `AuthenticationExtension` methods. It covers logging in, asserting login status, asserting the logged-in user's identity, logging out, and asserting the logged-out status. This example assumes the existence of login and logout routes and corresponding UI elements like 'Login' and 'Logout' links. ```php public function testDemo(): void { $this->browser() // goes to the /login page, fills email/password fields, // and presses the Login button ->loginAs('kevin@example.com', 'password') // asserts text "Logout" exists (assumes you have a logout link when users are logged in) ->assertLoggedIn() // asserts email exists as text (assumes you display the user's email when they are logged in) ->assertLoggedInAs('kevin@example.com') // goes to the /logout page ->logout() // asserts text "Login" exists (assumes you have a login link when users not logged in) ->assertNotLoggedIn() ; } ``` -------------------------------- ### Zenstruck Browser Convenience Methods and Utilities Source: https://github.com/zenstruck/browser/blob/1.x/README.md Illustrates advanced usage patterns including custom logic execution via the `use` method, accessing underlying browser components like the cookie jar, and leveraging debugging utilities like `dump` and `dd`. It also shows how to save page source and access the `DomCrawler` instance. ```php /** @var \Zenstruck\Browser $browser **/ $browser ->use(function() { // do something without breaking }) ->use(function(\Zenstruck\Browser $browser) { // access the current Browser instance }) ->use(function(\Symfony\Component\BrowserKit\AbstractBrowser $browser) { // access the "inner" browser }) ->use(function(\Symfony\Component\BrowserKit\CookieJar $cookieJar) { // access the cookie jar $cookieJar->expire('MOCKSESSID'); }) ->use(function(\Zenstruck\Browser $browser, \Symfony\Component\DomCrawler\Crawler $crawler) { // access the current Browser instance and the current crawler }) ->crawler() // Symfony\Component\DomCrawler\Crawler instance for the current response ->content() // string - raw response body // save the raw source of the current page // by default, saves to "/var/browser/source" // configure with "BROWSER_SOURCE_DIR" env variable ->saveSource('source.txt') // the following use symfony/var-dumper's dump() function and continue ->dump() // raw response body ->dump('h1') // html element ->dump('foo') // if json response, array key ->dump('foo.*.baz') // if json response, JMESPath notation can be used // the following use symfony/var-dumper's dd() function ("dump & die") ->dd() // raw response body or array if json ->dd('h1') // html element ->dd('foo') // if json response, array key ->dd('foo.*.baz') // if json response, JMESPath notation can be used ; ``` -------------------------------- ### Basic Symfony Functional Test with zenstruck/browser Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates a basic functional test case using the zenstruck/browser library to visit a post, assert its content, fill a form, submit it, and verify the result. This snippet showcases direct interaction with HTML elements and form fields. ```php public function testViewPostAndAddComment() { // assumes a "Post" is in the database with an id of 3 $this->browser() ->visit('/posts/3') ->assertSuccessful() ->assertSeeIn('title', 'My First Post') ->assertSeeIn('h1', 'My First Post') ->assertNotSeeElement('#comments') ->fillField('Comment', 'My First Comment') ->click('Submit') ->assertOn('/posts/3') ->assertSeeIn('#comments', 'My First Comment') ; } ``` -------------------------------- ### PantherBrowser Extra Methods - PHP Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates various advanced methods available on the PantherBrowser class for testing. These include interactive pausing, screenshotting, console log management, element assertions, waiting utilities, mouse interactions, and debugging helpers. Requires PantherBrowser instance. ```php /** @var \Zenstruck\Browser\PantherBrowser $browser **/ $browser // pauses the tests and enters "interactive mode" which // allows you to investigate the current state in the browser // (requires the env variable PANTHER_NO_HEADLESS=1) ->pause() // take a screenshot of the current browser state // by default, saves to "/var/browser/screenshots" // configure with "BROWSER_SCREENSHOT_DIR" env variable ->takeScreenshot('screenshot.png') // save the browser's javascript console error log // by default, saves to "/var/browser/console-log" // configure with "BROWSER_CONSOLE_LOG_DIR" env variable ->saveConsoleLog('console.log') // check if element is visible in the browser ->assertVisible('.selector') ->assertNotVisible('.selector') // wait x milliseconds ->wait(1000) // 1 second ->waitUntilVisible('.selector') ->waitUntilNotVisible('.selector') ->waitUntilSeeIn('.selector', 'some text') ->waitUntilNotSeeIn('.selector', 'some text') ->doubleClick('Link') ->rightClick('Link') // dump() the browser's console error log ->dumpConsoleLog() // dd() the browser's console error log ->ddConsoleLog() // dd() and take screenshot (default filename is "screenshot.png") ->ddScreenshot() ; ``` -------------------------------- ### Symfony Functional Test with zenstruck/browser and zenstruck/foundry Source: https://github.com/zenstruck/browser/blob/1.x/README.md Illustrates an enhanced functional test using zenstruck/browser in conjunction with zenstruck/foundry. This approach leverages factory patterns to create test data, leading to more readable and maintainable test code. ```php public function testViewPostAndAddComment() { $post = PostFactory::new()->create(['title' => 'My First Post']); $this->browser() ->visit("/posts/{$post->getId()}") ->assertSuccessful() ->assertSeeIn('title', 'My First Post') ->assertSeeIn('h1', 'My First Post') ->assertNotSeeElement('#comments') ->fillField('Comment', 'My First Comment') ->click('Submit') ->assertOn("/posts/{$post->getId()}") ->assertSeeIn('#comments', 'My First Comment') ; } ``` -------------------------------- ### Use Custom HttpOptions in Tests Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates how to use a custom HttpOptions class (e.g., AppHttpOptions) to make HTTP requests, simplifying the process compared to manually specifying options like headers and JSON content. ```php use Zenstruck\Browser\HttpOptions; /** @var \Zenstruck\Browser\KernelBrowser $browser **/ $browser // instead of ->post('/api/endpoint', HttpOptions::json()->withHeader('X-Token', 'my-token')) // use your ApiHttpOptions object ->post('/api/endpoint', AppHttpOptions::api('my-token')) ; ``` -------------------------------- ### Set Default HttpOptions for Browser Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates how to set default HTTP options, such as headers, for all requests made by a specific browser instance. These defaults can be overridden by per-request options. ```php /** @var \Zenstruck\Browser\KernelBrowser $browser **/ $browser ->setDefaultHttpOptions(['headers' => ['X-Token' => 'my-token']]) // now all http requests will have the X-Token header ->get('/endpoint') // "per-request" options will be merged with the default ->get('/endpoint', ['headers' => ['Another' => 'Header']]) ; ``` -------------------------------- ### Create Custom HttpOptions Class Source: https://github.com/zenstruck/browser/blob/1.x/README.md Illustrates creating a custom HttpOptions class to encapsulate common request configurations, like API requests with specific headers and JSON payloads. This promotes code reuse and readability. ```php namespace App\Tests; use Zenstruck\Browser\HttpOptions; class AppHttpOptions extends HttpOptions { public static function api(string $token, $json = null): self { return self::json($json) ->withHeader('X-Token', $token) ; } } ``` -------------------------------- ### Extend KernelBrowser for Custom Assertions Source: https://github.com/zenstruck/browser/blob/1.x/README.md Shows how to create a custom browser class (AppBrowser) by extending KernelBrowser and adding custom assertion methods, such as assertHasToolbar(). This allows for domain-specific testing functionalities. ```php namespace App\Tests; use Zenstruck\Browser\KernelBrowser; class AppBrowser extends KernelBrowser { public function assertHasToolbar(): self { return $this->assertSeeElement('#toolbar'); } } ``` -------------------------------- ### KernelBrowser: Response Assertions and Request Manipulation (PHP) Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates how to use KernelBrowser to make assertions on HTTP responses, including status codes, headers, and content types. It also shows methods for controlling exception handling, request rebooting, redirect following, and profiling. ```php /** @var \Zenstruck\Browser\KernelBrowser $browser **/ $browser // response assertions ->assertStatus(200) ->assertSuccessful() // 2xx status code ->assertRedirected() // 3xx status code ->assertHeaderEquals('Content-Type', 'text/html; charset=UTF-8') ->assertHeaderContains('Content-Type', 'html') ->assertHeaderEquals('X-Not-Present-Header', null) // helpers for quickly checking the content type ->assertJson() ->assertXml() ->assertHtml() ->assertContentType('zip') // by default, exceptions are caught and converted to a response // use the BROWSER_CATCH_EXCEPTIONS environment variable to change default // this disables that behaviour allowing you to use TestCase::expectException() ->throwExceptions() // enable catching exceptions ->catchExceptions() // by default, the kernel is rebooted between requests // this disables this behaviour ->disableReboot() // re-enable rebooting between requests if previously disabled ->enableReboot() // enable the profiler for the next request (if not globally enabled) ->withProfiling() // by default, redirects are followed, this disables that behaviour // use the BROWSER_FOLLOW_REDIRECTS environment variable to change default ->interceptRedirects() // enable following redirects // if currently on a redirect response, follows ->followRedirects() ->followRedirect() // follows all redirects by default ->followRedirect(1) // just follow 1 redirect // combination of assertRedirected(), followRedirect(), assertOn() ->assertRedirectedTo('/some/page') // follows all redirects by default ->assertRedirectedTo('/some/page', 1) // just follow 1 redirect // combination of interceptRedirects(), withProfiling(), click() // useful for submitting forms and making assertions on the "redirect response" ->clickAndIntercept('button') // exception assertions for the "next request" ->expectException(MyException::class, 'the message') ->post('/url/that/throws/exception') // fails if above exception not thrown ->expectException(MyException::class, 'the message') ->click('link or button') // fails if above exception not thrown ; ``` -------------------------------- ### KernelBrowser: Authentication Assertions and Helpers (PHP) Source: https://github.com/zenstruck/browser/blob/1.x/README.md Illustrates how to use KernelBrowser to authenticate a user for subsequent requests and perform assertions related to authentication status. It covers asserting if a user is authenticated, not authenticated, or authenticated as a specific user. ```php /** @var \Zenstruck\Browser\KernelBrowser $browser **/ $browser // authenticate a user for subsequent actions ->actingAs($user) // \Symfony\Component\Security\Core\User\UserInterface // fail if authenticated ->assertNotAuthenticated() // fail if NOT authenticated ->assertAuthenticated() // fails if NOT authenticated as "kbond" ->assertAuthenticated('kbond') // \Symfony\Component\Security\Core\User\UserInterface ->assertAuthenticated($user) ; ``` -------------------------------- ### PHPUnit Test with Zenstruck Browser Source: https://github.com/zenstruck/browser/blob/1.x/README.md Demonstrates how to use the `HasBrowser` trait in PHPUnit tests to interact with KernelBrowser and PantherBrowser. Requires specific base test classes depending on the browser used. Shows basic navigation and assertion. ```php namespace App\Tests; use PHPUnit\Framework\TestCase; use Zenstruck\Browser\Test\HasBrowser; class MyTest extends TestCase { use HasBrowser; /** * Requires this test extends Symfony\Bundle\FrameworkBundle\Test\KernelTestCase * or Symfony\Bundle\FrameworkBundle\Test\WebTestCase. */ public function test_using_kernel_browser(): void { $this->browser() ->visit('/my/page') ->assertSeeIn('h1', 'Page Title') ; } /** * Requires this test extends Symfony\Component\Panther\PantherTestCase. */ public function test_using_panther_browser(): void { $this->pantherBrowser() ->visit('/my/page') ->assertSeeIn('h1', 'Page Title') ; } } ``` -------------------------------- ### Handle Form Submission and Clear Input with jQuery Source: https://github.com/zenstruck/browser/blob/1.x/tests/Fixture/files/javascript.html This snippet demonstrates how to handle a form submission by capturing input value and displaying it, and also how to clear input and output fields using jQuery. It attaches click event listeners to buttons for these actions. ```javascript $(function() { $('#submit').click(function() { $('#output').text($('#input').val()); }); $('#clear').click(function() { $('#input').val(''); $('#output').text(''); }); }); ``` -------------------------------- ### Assert JSON Responses with KernelBrowser and JMESPath Source: https://github.com/zenstruck/browser/blob/1.x/README.md Shows how to make assertions on JSON responses using JMESPath expressions. This requires the 'mtdowling/jmespath.php' package. It covers basic assertions, accessing the JSON crawler for more detailed checks, and using the crawler within a closure for contextual assertions. ```php **/ /** @var \Zenstruck\Browser\KernelBrowser $browser **/ $browser ->get('/api/endpoint') ->assertJson() // ensures the content-type is application/json ->assertJsonMatches('foo.bar.baz', 1) // automatically calls ->assertJson() ->assertJsonMatches('foo.*.baz', [1, 2, 3]) ->assertJsonMatches('length(foo)', 3) ->assertJsonMatches('"@some:thing"', 6) // note: special characters like : and @ need to be wrapped in quotes ; // access the json "crawler" $json = $browser ->get('/api/endpoint') ->json() ; $json->assertMatches('foo.bar.baz', 1); $json->assertHas('foo.bar.baz'); $json->assertMissing('foo.bar.boo'); $json->search('foo.bar.baz'); // mixed (the found value at "JMESPath expression") $json->decoded(); // the decoded json (string) $json; // the json string pretty-printed // "use" the json crawler $json = $browser ->get('/api/endpoint') ->use(function(Zenstruck\Browser\Json $json) { // Json acts like a proxy of zenstruck/assert Expectation class $json->hasCount(5); $json->contains('foo'); // assert on children: the closure gets Json object contextualized on given selector // {"foo": "bar"} $json->assertThat('foo', fn(Json $json) => $json->equals('bar')) // assert on each element of an array // {"foo": [1, 2, 3]} $json->assertThatEach('foo', fn(Json $json) => $json->isGreaterThan(0)); // assert json matches given json schema $json->assertMatchesSchema(file_get_contents('/path/to/json-schema.json')); }) ; ``` -------------------------------- ### Configure Custom Browser Class via Environment Variable Source: https://github.com/zenstruck/browser/blob/1.x/README.md Explains how to set an environment variable (KERNEL_BROWSER_CLASS or PANTHER_BROWSER_CLASS) to tell Zenstruck Browser to use your custom browser implementation instead of the default. ```text # For KernelBrowser: KERNEL_BROWSER_CLASS=App\Tests\AppBrowser # For PantherBrowser: PANTHER_BROWSER_CLASS=App\Tests\AppBrowser ``` -------------------------------- ### KernelBrowser: Profiler and Data Collector Access (PHP) Source: https://github.com/zenstruck/browser/blob/1.x/README.md Shows how to access the Symfony Profiler and specific data collectors, such as the database query collector, after a request has been made using KernelBrowser. This requires profiling to be enabled. ```php // Access the Symfony Profiler for the last request $queryCount = $browser // If profiling is not globally enabled for tests, ->withProfiling() // must be called before the request. ->profile()->getCollector('db')->getQueryCount() ; // "use" a specific data collector $browser->use(function(\Symfony\Component\HttpKernel\DataCollector\RequestDataCollector $collector) { // ... }); ``` -------------------------------- ### JSON Assertions Source: https://github.com/zenstruck/browser/blob/1.x/README.md This section covers how to make assertions about JSON responses using JMESPath expressions and the `json()` crawler object. ```APIDOC ## JSON Assertions ### Description Make assertions about JSON responses using JMESPath expressions and the `json()` crawler object. ### Method GET, PUT, POST, DELETE (typically after an HTTP request) ### Endpoint /api/endpoint ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php get('/api/endpoint') ->assertJson() ->assertJsonMatches('foo.bar.baz', 1) ->assertJsonMatches('foo.*.baz', [1, 2, 3]) ->assertJsonMatches('length(foo)', 3) ->assertJsonMatches('"@some:thing"', 6) ; // Accessing the json crawler $json = $browser->get('/api/endpoint')->json(); $json->assertMatches('foo.bar.baz', 1); $json->assertHas('foo.bar.baz'); $json->assertMissing('foo.bar.boo'); $json->search('foo.bar.baz'); $json->decoded(); (string) $json; // Using the json crawler in a closure $browser ->get('/api/endpoint') ->use(function(\Zenstruck\Browser\Json $json) { $json->hasCount(5); $json->contains('foo'); $json->assertThat('foo', fn(\Zenstruck\Browser\Json $json) => $json->equals('bar')); $json->assertThatEach('foo', fn(\Zenstruck\Browser\Json $json) => $json->isGreaterThan(0)); $json->assertMatchesSchema(file_get_contents('/path/to/json-schema.json')); }); ``` ### Response #### Success Response (200) * **json** (object/array) - The decoded JSON response. #### Response Example ```json { "foo": { "bar": { "baz": 1 } }, "some:thing": 6 } ``` ``` -------------------------------- ### PHP Authentication Extension for Browser Testing Source: https://github.com/zenstruck/browser/blob/1.x/README.md This PHP trait provides methods for browser-based authentication, including logging in, logging out, and asserting login status. It's designed to be used with Zenstruck Browser for streamlined testing of authentication flows. No external dependencies beyond Zenstruck Browser are strictly required for the trait itself. ```php namespace App\Tests\Browser; trait AuthenticationExtension { public function loginAs(string $username, string $password): self { return $this ->visit('/login') ->fillField('email', $username) ->fillField('password', $password) ->click('Login') ; } public function logout(): self { return $this->visit('/logout'); } public function assertLoggedIn(): self { $this->assertSee('Logout'); return $this; } public function assertLoggedInAs(string $user): self { $this->assertSee($user); return $this; } public function assertNotLoggedIn(): self { $this->assertSee('Login'); return $this; } } ``` -------------------------------- ### Configure zenstruck/browser PHPUnit Extension (v8/v9) Source: https://github.com/zenstruck/browser/blob/1.x/README.md XML configuration snippet for PHPUnit versions 8 and 9 to enable the zenstruck/browser extension. This extension automatically saves browser artifacts on test failures. ```xml ``` -------------------------------- ### PHP Custom Browser Class with Authentication Extension Source: https://github.com/zenstruck/browser/blob/1.x/README.md This PHP class extends Zenstruck\Browser\KernelBrowser and incorporates the custom AuthenticationExtension trait. This allows for the authentication methods defined in the trait to be directly available on instances of this custom browser class. It requires the AuthenticationExtension trait and Zenstruck\Browser\KernelBrowser. ```php namespace App\Tests; use App\Tests\Browser\AuthenticationExtension; use Zenstruck\Browser\KernelBrowser; class AppBrowser extends KernelBrowser { use AuthenticationExtension; } ``` -------------------------------- ### Handle Console Error Logging and Exception Throwing with JavaScript Source: https://github.com/zenstruck/browser/blob/1.x/tests/Fixture/files/javascript.html This snippet shows how to log an error message to the browser's console using console.error and how to throw a new Error object. These are useful for debugging and handling unexpected situations in JavaScript applications. ```javascript $(function() { $('#log-error').click(function() { console.error('console.error message'); }); $('#throw-error').click(function() { throw new Error('error object message'); }); }); ``` -------------------------------- ### Multiple PantherBrowser Instances - PHP Source: https://github.com/zenstruck/browser/blob/1.x/README.md Illustrates how to obtain and use multiple independent PantherBrowser instances within a single test case using the `HasBrowser` trait. This is useful for scenarios requiring concurrent browser interactions or testing real-time features like websockets. Assumes a Symfony testing environment. ```php namespace App\Tests; use Symfony\Component\Panther\PantherTestCase; use Zenstruck\Browser\Test\HasBrowser; class MyTest extends PantherTestCase { use HasBrowser; public function testDemo(): void { $browser1 = $this->pantherBrowser() ->visit('/my/page') // ... ; $browser2 = $this->pantherBrowser() ->visit('/my/page') // ... ; } } ``` -------------------------------- ### Configure zenstruck/browser PHPUnit Extension (v10+) Source: https://github.com/zenstruck/browser/blob/1.x/README.md XML configuration snippet for PHPUnit version 10 and above to enable the zenstruck/browser extension. This configuration enables automatic saving of browser artifacts during test execution failures. ```xml ... ``` -------------------------------- ### Show and Hide Elements with jQuery Source: https://github.com/zenstruck/browser/blob/1.x/tests/Fixture/files/javascript.html This snippet shows how to control the visibility of HTML elements using jQuery. It includes functions to explicitly show an element, explicitly hide an element, and toggle the visibility of an element with a single click. ```javascript $(function() { $('#show').click(function() { $('#show-box').show(); }); $('#hide').click(function() { $('#hide-box').hide(); }); $('#toggle').click(function() { $('#toggle-box').toggle(); }); }); ``` -------------------------------- ### Set Default HttpOptions in Test Case Configuration Source: https://github.com/zenstruck/browser/blob/1.x/README.md Shows how to configure default HTTP options for the browser within a test class by overriding the browser() method. This ensures all tests in the class inherit the specified default options. ```php namespace App\Tests; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Zenstruck\Browser\KernelBrowser; use Zenstruck\Browser\Test\HasBrowser; class MyTest extends KernelTestCase { use HasBrowser { browser as baseKernelBrowser; } public function testDemo(): void { $this->browser() // all http requests in this test class will have the X-Token header ->get('/endpoint') // "per-request" options will be merged with the default ->get('/endpoint', ['headers' => ['Another' => 'Header']]) ; } protected function browser(): KernelBrowser { return $this->baseKernelBrowser() ->setDefaultHttpOptions(['headers' => ['X-Token' => 'my-token']]) ; } } ``` -------------------------------- ### Implement Delayed Element Display with jQuery setTimeout Source: https://github.com/zenstruck/browser/blob/1.x/tests/Fixture/files/javascript.html This snippet demonstrates how to use jQuery's setTimeout function to delay the display of an HTML element. After a specified delay (500 milliseconds in this case), the element with the ID 'timeout-box' will be shown. ```javascript $(function() { window.setTimeout(function() { $('#timeout-box').show(); }, 500); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.