• Stars
    star
    497
  • Rank 85,292 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Provides backwards compatibility for BrowserKit testing in the latest Laravel release.

Laravel BrowserKit Testing

Build Status Total Downloads Latest Stable Version License

Introduction

Laravel BrowserKit Testing provides a very fluent API for making HTTP requests to your application, examining the output, and even filling out forms.

Official Documentation

Installation

First, install this package:

composer require laravel/browser-kit-testing --dev

Next, modify your application's base TestCase class to extend Laravel\BrowserKitTesting\TestCase instead of Illuminate\Foundation\Testing\TestCase:

<?php

namespace Tests;

use Laravel\BrowserKitTesting\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    public $baseUrl = 'http://localhost';

    // ...
}

No other modifications to your tests should be necessary.

Usage

To get started with a simple example, take a look at the test defined below:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('Laravel')
             ->dontSee('Rails');
    }
}

The visit method makes a GET request into the application. The see method asserts that we should see the given text in the response returned by the application. The dontSee method asserts that the given text is not returned in the application response. This is the most basic application test available in Laravel.

You may also use the 'visitRoute' method to make a 'GET' request via a named route:

$this->visitRoute('profile');

$this->visitRoute('profile', ['user' => 1]);

Interacting With Your Application

Of course, you can do much more than simply assert that text appears in a given response. Let's take a look at some examples of clicking links and filling out forms:

Interacting With Links

In this test, we will make a request to the application, "click" a link in the returned response, and then assert that we landed on a given URI. For example, let's assume there is a link in our response that has a text value of "About Us":

<a href="/about-us">About Us</a>

Now, let's write a test that clicks the link and asserts the user lands on the correct page:

public function testBasicExample()
{
    $this->visit('/')
         ->click('About Us')
         ->seePageIs('/about-us');
}

You may also check that the user has arrived at the correct named route using the seeRouteIs method:

->seeRouteIs('profile', ['user' => 1]);

Interacting With Forms

Laravel also provides several methods for testing forms. The type, select, check, attach, and press methods allow you to interact with all of your form's inputs. For example, let's imagine this form exists on the application's registration page:

<form action="/register" method="POST">
    {{ csrf_field() }}

    <div>
        Name: <input type="text" name="name">
    </div>

    <div>
        <input type="checkbox" value="yes" name="terms"> Accept Terms
    </div>

    <div>
        <input type="submit" value="Register">
    </div>
</form>

We can write a test to complete this form and inspect the result:

public function testNewUserRegistration()
{
    $this->visit('/register')
         ->type('Taylor', 'name')
         ->check('terms')
         ->press('Register')
         ->seePageIs('/dashboard');
}

Of course, if your form contains other inputs such as radio buttons or drop-down boxes, you may easily fill out those types of fields as well. Here is a list of each form manipulation method:

Method Description
$this->type($text, $elementName) "Type" text into a given field.
$this->select($value, $elementName) "Select" a radio button or drop-down field.
$this->check($elementName) "Check" a checkbox field.
$this->uncheck($elementName) "Uncheck" a checkbox field.
$this->attach($pathToFile, $elementName) "Attach" a file to the form.
$this->press($buttonTextOrElementName) "Press" a button with the given text or name.
File Inputs

If your form contains file inputs, you may attach files to the form using the attach method:

public function testPhotoCanBeUploaded()
{
    $this->visit('/upload')
         ->attach($pathToFile, 'photo')
         ->press('Upload')
         ->see('Upload Successful!');
}

Testing JSON APIs

Laravel also provides several helpers for testing JSON APIs and their responses. For example, the json, get, post, put, patch, and delete methods may be used to issue requests with various HTTP verbs. You may also easily pass data and headers to these methods. To get started, let's write a test to make a POST request to /user and assert that the expected data was returned:

<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->json('POST', '/user', ['name' => 'Sally'])
             ->seeJson([
                 'created' => true,
             ]);
    }
}

{tip} The seeJson method converts the given array into JSON, and then verifies that the JSON fragment occurs anywhere within the entire JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

Verifying Exact Match

If you would like to verify that the given array is an exact match for the JSON returned by the application, you should use the seeJsonEquals method:

<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->json('POST', '/user', ['name' => 'Sally'])
             ->seeJsonEquals([
                 'created' => true,
             ]);
    }
}

Verifying Structural Match

It is also possible to verify that a JSON response adheres to a specific structure. In this scenario, you should use the seeJsonStructure method and pass it your expected JSON structure:

<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->get('/user/1')
             ->seeJsonStructure([
                 'name',
                 'pet' => [
                     'name',
                     'age',
                 ],
             ]);
    }
}

The above example illustrates an expectation of receiving a name attribute and a nested pet object with its own name and age attributes. seeJsonStructure will not fail if additional keys are present in the response. For example, the test would still pass if the pet had a weight attribute.

You may use the * to assert that the returned JSON structure has a list where each list item contains at least the attributes found in the set of values:

<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        // Assert that each user in the list has at least an id, name and email attribute.
        $this->get('/users')
             ->seeJsonStructure([
                 '*' => [
                     'id',
                     'name',
                     'email',
                 ],
             ]);
    }
}

You may also nest the * notation. In this case, we will assert that each user in the JSON response contains a given set of attributes and that each pet on each user also contains a given set of attributes:

$this->get('/users')
     ->seeJsonStructure([
         '*' => [
             'id', 'name', 'email', 'pets' => [
                 '*' => [
                     'name',
                     'age',
                 ],
             ],
         ],
     ]);

Sessions / Authentication

Laravel provides several helpers for working with the session during testing. First, you may set the session data to a given array using the withSession method. This is useful for loading the session with data before issuing a request to your application:

<?php

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $this->withSession(['foo' => 'bar'])
             ->visit('/');
    }
}

Of course, one common use of the session is for maintaining state for the authenticated user. The actingAs helper method provides a simple way to authenticate a given user as the current user. For example, we may use a model factory to generate and authenticate a user:

<?php

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $user = factory(App\User::class)->create();

        $this->actingAs($user)
             ->withSession(['foo' => 'bar'])
             ->visit('/')
             ->see('Hello, '.$user->name);
    }
}

You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the actingAs method:

$this->actingAs($user, 'api')

Disabling Middleware

When testing your application, you may find it convenient to disable middleware for some of your tests. This will allow you to test your routes and controller in isolation from any middleware concerns. Laravel includes a simple WithoutMiddleware trait that you can use to automatically disable all middleware for the test class:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use WithoutMiddleware;

    //
}

If you would like to only disable middleware for a few test methods, you may call the withoutMiddleware method from within the test methods:

<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->withoutMiddleware();

        $this->visit('/')
             ->see('Laravel');
    }
}

Custom HTTP Requests

If you would like to make a custom HTTP request into your application and get the full Illuminate\Http\Response object, you may use the call method:

public function testApplication()
{
    $response = $this->call('GET', '/');

    $this->assertEquals(200, $response->status());
}

If you are making POST, PUT, or PATCH requests you may pass an array of input data with the request. Of course, this data will be available in your routes and controller via the Request instance:

$response = $this->call('POST', '/user', ['name' => 'Taylor']);

PHPUnit Assertions

Laravel provides a variety of custom assertion methods for PHPUnit tests:

Method Description
->assertResponseOk(); Assert that the client response has an OK status code.
->assertResponseStatus($code); Assert that the client response has a given code.
->assertViewHas($key, $value = null); Assert that the response view has a given piece of bound data.
->assertViewHasAll(array $bindings); Assert that the view has a given list of bound data.
->assertViewMissing($key); Assert that the response view is missing a piece of bound data.
->assertRedirectedTo($uri, $with = []); Assert whether the client was redirected to a given URI.
->assertRedirectedToRoute($name, $parameters = [], $with = []); Assert whether the client was redirected to a given route.
->assertRedirectedToAction($name, $parameters = [], $with = []); Assert whether the client was redirected to a given action.
->assertSessionHas($key, $value = null); Assert that the session has a given value.
->assertSessionHasAll(array $bindings); Assert that the session has a given list of values.
->assertSessionHasErrors($bindings = [], $format = null); Assert that the session has errors bound.
->assertHasOldInput(); Assert that the session has old input.
->assertSessionMissing($key); Assert that the session is missing a given key.

Contributing

Thank you for considering contributing to BrowserKit Testing! The contribution guide can be found in the Laravel documentation.

Code of Conduct

In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

License

Laravel BrowserKit Testing is open-sourced software licensed under the MIT license.

More Repositories

1

laravel

Laravel is a web application framework with expressive, elegant syntax. Weโ€™ve already laid the foundation for your next big idea โ€” freeing you to create without sweating the small things.
PHP
75,490
star
2

framework

The Laravel Framework.
PHP
30,766
star
3

lumen

The Laravel Lumen Framework.
PHP
7,644
star
4

tinker

Powerful REPL for the Laravel framework.
PHP
7,241
star
5

socialite

Laravel wrapper around OAuth 1 & OAuth 2 libraries.
PHP
5,407
star
6

telescope

An elegant debug assistant for the Laravel framework.
PHP
4,631
star
7

homestead

Shell
3,850
star
8

jetstream

Tailwind scaffolding for the Laravel framework.
PHP
3,804
star
9

horizon

Dashboard and code-driven configuration for Laravel queues.
PHP
3,719
star
10

octane

Supercharge your Laravel application's performance.
PHP
3,533
star
11

passport

Laravel Passport provides OAuth2 server support to Laravel.
PHP
3,184
star
12

docs

The Laravel documentation.
2,816
star
13

sanctum

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.
PHP
2,623
star
14

pint

Laravel Pint is an opinionated PHP code style fixer for minimalists.
PHP
2,580
star
15

breeze

Minimal Laravel authentication scaffolding with Blade, Vue, or React + Tailwind.
PHP
2,469
star
16

valet

A more enjoyable local development experience for Mac.
PHP
2,437
star
17

ui

Laravel UI utilities and presets.
PHP
2,338
star
18

cashier-stripe

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.
PHP
2,291
star
19

dusk

Laravel Dusk provides simple end-to-end testing and browser automation.
PHP
1,788
star
20

envoy

Elegant SSH tasks for PHP.
PHP
1,545
star
21

fortify

Backend controllers and scaffolding for Laravel authentication.
PHP
1,500
star
22

sail

Docker files for running a basic Laravel application.
Shell
1,468
star
23

lumen-framework

The Laravel Lumen Framework.
PHP
1,455
star
24

scout

Laravel Scout provides a driver based solution to searching your Eloquent models.
PHP
1,455
star
25

pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.
PHP
1,154
star
26

breeze-next

An application / authentication starter kit frontend in Next.js for Laravel Breeze.
JavaScript
1,116
star
27

echo

Laravel Echo library for beautiful Pusher and Ably integration.
TypeScript
1,085
star
28

elixir

Fluent API for Gulp.
JavaScript
1,080
star
29

settler

Shell
1,013
star
30

ideas

Issues board used for Laravel internals discussions.
943
star
31

slack-notification-channel

Slack Notification Channel for laravel.
PHP
829
star
32

vite-plugin

Laravel plugin for Vite.
TypeScript
744
star
33

helpers

Provides backwards compatibility for helpers in the latest Laravel release.
PHP
735
star
34

vonage-notification-channel

Vonage Notification Channel for Laravel.
PHP
709
star
35

pail

Dive into your Laravel application's log files directly from the console. ๐Ÿชฃ
PHP
564
star
36

nova-issues

550
star
37

laravel.com

The source code of the official Laravel website.
Blade
531
star
38

installer

The Laravel application installer.
PHP
527
star
39

folio

Page based routing for Laravel.
PHP
523
star
40

forge-sdk

The official Laravel Forge PHP SDK.
PHP
491
star
41

serializable-closure

Laravel Serializable Closure provides an easy and secure way to serialize closures in PHP.
PHP
434
star
42

spark-legacy

PHP
427
star
43

pennant

A simple, lightweight library for managing feature flags.
PHP
408
star
44

vapor-core

The core service providers and runtime client for Laravel Vapor.
PHP
396
star
45

quickstart-basic

A sample task list application.
PHP
391
star
46

cashier-mollie

PHP
377
star
47

prompts

Beautiful and user-friendly forms for your command-line PHP applications.
PHP
357
star
48

spark-installer

PHP
314
star
49

nova-docs

The Laravel Nova documentation.
TypeScript
310
star
50

vapor-cli

The CLI client for interacting with Laravel Vapor.
PHP
294
star
51

vapor-ui

The Laravel Vapor UI.
Vue
265
star
52

quickstart-intermediate

A sample task list application with authentication.
PHP
262
star
53

blog-contest-may-mayhem

244
star
54

cashier-paddle

Cashier Paddle provides an expressive, fluent interface to Paddle's subscription billing services.
PHP
226
star
55

forge-cli

The Laravel Forge CLI.
PHP
219
star
56

spark-aurelius

PHP
200
star
57

art

Laravel logo and other artwork.
190
star
58

spark-tests

174
star
59

cashier-braintree

PHP
164
star
60

vapor-php-build

Dockerfile
131
star
61

nova-log-viewer

A Laravel Nova tool for viewing your application logs
PHP
118
star
62

legacy-factories

PHP
118
star
63

nova-js

JavaScript
113
star
64

jetstream-js

JavaScript
107
star
65

forge-monitor

PHP
105
star
66

forge-database-backups

Shell
104
star
67

precognition

Anticipate the outcome of a future HTTP request.
TypeScript
96
star
68

bootcamp.laravel.com

Laravel Bootcamp
PHP
95
star
69

nova-dusk-suite

PHP
93
star
70

vapor-laravel-template

PHP
86
star
71

lumen-docs

The Lumen documentation.
84
star
72

lumen-installer

PHP
76
star
73

jetstream-docs

The Jetstream documentation.
TypeScript
69
star
74

legacy-encrypter

PHP
60
star
75

.github

Source code of the default community health files for the Laravel organization.
52
star
76

vapor-dockerfiles

Dockerfile
49
star
77

vapor-docs

The Vapor documentation.
TypeScript
49
star
78

forge-docs

The Forge documentation.
TypeScript
38
star
79

discord-bot

TypeScript
37
star
80

vapor-js

JavaScript
36
star
81

spark-docs

The Spark Classic documentation.
27
star
82

nova-mix

JavaScript
26
star
83

spark-aurelius-mollie

Laravel Spark, Mollie edition
PHP
26
star
84

envoyer-docs

The Envoyer documentation.
TypeScript
23
star
85

sail-server

The build website for new Laravel Sail apps.
PHP
19
star
86

facade-documenter

Laravel's Facade docblock generator.
PHP
15
star
87

spark-next-docs

The Spark documentation.
TypeScript
9
star