Laravel View Test Assertions
Few additional assertions for testing Laravel views.
Why
Laravel has well established and documented way of testing requests
. However, this is not the case for the views. I always felt that views in Laravel are neglected when it comes to testing, however being confident that form
, submit button
, and input fields
are present is essential.
Granted, you can use Dusk
, but it is significantly slower than regular feature tests and adding Dusk
as part of the test suite is not always desired.
That's why I created this package. It is my attempt/proposal for adding a bit of TDD concept to the views too. Hope you like it.
Installation
composer require --dev jcergolj/laravel-view-test-assertions
Assertions
assertViewHasForm(string $method = null, string $action = null)
assertFormHasCSRF()
assertFormHasSubmitButton(string $type = 'submit', string $text = null)
assertFormHasDropdown(string $name)
assertFormHasField(string $type, string $name = null)
assertFormHasField(string $type, string $name = null)
assertElementHasChild(string $parentSelector, string $childSelector)
assertFieldHasValidationErrorMsg(string $errorMsg)
Example
View
// resources/welcome.blade.php
<span class="hljs-code">Laravel</span>
Example Test
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function test_example()
{
$response = $this->get('/');
$response->assertStatus(200)
->assertViewHasForm()
->assertViewHasForm('post')
->assertViewHasForm(null, '/users')
->assertViewHasForm('post', '/users')
->assertFieldHasValidationErrorMsg(trans('validation.alpha', ['attribute' => 'First Name']))
->assertFormHasCSRF()
->assertFormHasField('text', 'first_name')
->assertFormHasField('select', 'age')
->assertFormHasDropdown('age')
->assertFormHasSubmitButton()
->assertElementHasChild('select[name="age"]', 'option[value="5"]')
->assertElementHasChild('select[name="age"]', 'option[plaintext="5 Years"]')
->assertElementHasChild('div#parent', 'div.child');
}
}