Jose Gabrielle Rivera
jgrivera.dev

jgrivera.dev

Using Laravel Orchid and PestPHP together

Photo by Earl Wilcox on Unsplash

Using Laravel Orchid and PestPHP together

Bridging two different worlds

Jose Gabrielle Rivera's photo
Jose Gabrielle Rivera
·Sep 23, 2022·

2 min read

Table of contents

  • Foreword
  • Problem
  • Solution
  • Closing Thoughts

Foreword

I recently converted our Laravel codebase to use PestPHP as our testing framework. The decision is great so far. I come from the JavaScript world where we commonly write tests using Jest. The syntax of PestPHP and Jest are extremely similar. This is something that I enjoy. It makes it absolutely fast to write tests in PHP.

Problem

I use Laravel Orchid to power the user interface of our administrator dashboard. It is also a great piece of software. It even has a nice feature for creating test screens using their provided ScreenTesting trait. I want to use this trait on my PestPHP tests. I want the trait to have complete type hints as well!

Solution

Luckily, PestPHP has this nice feature where you can write a custom helper function.

Just add the following code in your tests/Pest.php file. Retrofit as needed:

<?php

use Orchid\Support\Testing\ScreenTesting;
use Orchid\Support\Testing\DynamicTestScreen;

uses(ScreenTesting::class)
    ->in('Feature/Orchid');

function screen(?string $name = null): DynamicTestScreen
{
    return test()->screen($name);
}

In the example above, I make the ScreenTesting trait available to my tests in the Feature/Orchid folder. I define the actual helper function called screen with appropriate type hints. Voila! it is readily made available to all my tests. It is that simple. We just bridged the two worlds together.

You can begin using the new helper function in a test, like so:

<?php

it('should show login screen', function () {
    $screen = screen('platform.login');

    $screen->display()
        ->assertSee('Login')
        ->assertSee('Sign in to your account');
});

Closing Thoughts

The test should pass. Congratulations! Now go write some more tests with your shiny new helper function.

  PASS  Tests\Feature\Orchid\Screens\LoginScreenTest
  ✓ it should show login screen

  Tests:  1 passed
  Time:   0.41s

I greatly admire the flexibility that PestPHP gives us. It was a nice developer experience to witness. As a developer myself, I aspire to deliver software that offers such flexibility and empowerment.

This is just a short blog post for today. Thanks for reading! 🥳

 
Share this