Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

O Testbench Dusk Laravel Package

wpstarter/o-testbench-dusk

Laravel Dusk testing harness for packages using Orchestra Testbench. Spin up a browser test environment with minimal app scaffolding to run end-to-end UI tests against your package during development and CI.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer in your WordPress project:

    composer require wpstarter/o-testbench-dusk
    

    Publish the configuration (if needed):

    php artisan vendor:publish --provider="WpStarter\TestBenchDusk\TestBenchDuskServiceProvider"
    
  2. Basic Dusk Test Create a test file in tests/Browser (e.g., ExampleTest.php):

    <?php
    namespace Tests\Browser;
    
    use WpStarter\TestBenchDusk\Browser;
    use WpStarter\TestBenchDusk\WordPress;
    
    class ExampleTest extends Browser
    {
        public function test_example()
        {
            $this->loginAsAdmin()
                 ->visit('/')
                 ->assertSee('Welcome to WordPress');
        }
    }
    

    Run the test:

    php artisan dusk
    
  3. Key Entry Points

    • Browser class: Extend this for Dusk tests.
    • WordPress trait: Provides WordPress-specific helpers (e.g., loginAsAdmin(), createPost()).
    • Configuration: Check config/testbench-dusk.php for browser drivers, WordPress paths, and defaults.

Implementation Patterns

1. WordPress-Specific Workflows

Authentication

$this->loginAsAdmin() // Logs in as admin user
     ->loginAs('editor@example.com', 'password123') // Custom user
     ->logout(); // Ends session

Content Management

$this->createPost([
    'title'   => 'Test Post',
    'content' => 'Hello, Dusk!',
    'status'  => 'publish',
])->assertPublished();

$this->updatePost(1, ['title' => 'Updated Title']);

Role/Capability Checks

$this->actingAsUser('editor@example.com')
     ->assertCan('edit_posts')
     ->assertCannot('manage_options');

2. Integration with Laravel TestBench

Hybrid Testing (Unit + Browser)

// tests/Feature/ExampleFeatureTest.php
public function test_post_creation()
{
    $post = factory(\App\Models\Post::class)->create();
    $this->assertDatabaseHas('posts', ['id' => $post->id]);
}

// tests/Browser/PostCreationTest.php
public function test_post_creation_via_ui()
{
    $this->createPost(['title' => 'UI Post'])
         ->assertSee('UI Post');
}

Shared Fixtures

Use DatabaseMigrations and DatabaseTransactions in both unit and browser tests:

use Tests\TestCase;
use WpStarter\TestBenchDusk\Browser;

class SharedTest extends TestCase
{
    use DatabaseMigrations; // Shared DB setup
}

class BrowserTest extends Browser
{
    use DatabaseTransactions; // Rollback after test
}

3. Customizing the Browser

Driver Configuration

Update config/testbench-dusk.php:

'driver' => 'chrome', // or 'firefox', 'remote'
'headless' => env('DUSK_HEADLESS', false),
'options' => [
    'args' => ['--no-sandbox', '--disable-dev-shm-usage'],
],

Custom Commands

Extend the Browser class to add reusable methods:

namespace Tests\Browser;

use WpStarter\TestBenchDusk\Browser as BaseBrowser;

class CustomBrowser extends BaseBrowser
{
    public function assertPluginActive($plugin)
    {
        $this->visit('/wp-admin/plugins.php')
             ->assertSee($plugin);
    }
}

Gotchas and Tips

1. Common Pitfalls

WordPress Not Booted

  • Issue: Tests fail with "WordPress not loaded" errors.
  • Fix: Ensure WP_TESTS_DIR is set in phpunit.xml:
    <env name="WP_TESTS_DIR" value="/path/to/wordpress-develop/tests/phpunit"/>
    

Session Persistence

  • Issue: Logins persist between tests (flaky tests).
  • Fix: Use DatabaseTransactions or clear cookies:
    $this->logout()->clearCookie();
    

Slow Tests

  • Issue: Dusk tests run slowly in CI.
  • Fix:
    • Use headless mode (--headless in Chrome args).
    • Parallelize tests with php artisan dusk --parallel.

2. Debugging Tips

Screenshot on Failure

Enable screenshots in phpunit.xml:

<env name="DUSK_SCREENSHOTS" value="storage/screenshots"/>

Access screenshots at storage/screenshots/.

Log Browser Output

Add this to TestBenchDuskServiceProvider:

Browser::macro('log', function () {
    file_put_contents(
        storage_path('logs/dusk.log'),
        $this->driver->getCurrentUrl() . "\n" . $this->driver->getPageSource(),
        FILE_APPEND
    );
});

WP Debug Mode

Enable in phpunit.xml:

<env name="WP_DEBUG" value="true"/>
<env name="WP_DEBUG_LOG" value="true"/>

3. Extension Points

Custom WordPress Helpers

Override the WordPress trait in your test class:

use WpStarter\TestBenchDusk\WordPress as BaseWordPress;

trait CustomWordPress
{
    use BaseWordPress;

    public function createCustomPostType()
    {
        // Custom logic
    }
}

Hook into WordPress Events

Use add_action in setUp():

public function setUp(): void
{
    add_action('wp_loaded', function() {
        // Modify WP behavior for tests
    });
    parent::setUp();
}

Mocking External APIs

Use Laravel’s HTTP testing helpers:

$this->mock(\Illuminate\Http\Client\PendingRequest::class)
     ->shouldReceive('get')
     ->andReturnResponse(['status' => 'success']);

4. Configuration Quirks

Path Resolving

  • WordPress paths (e.g., WP_CONTENT_DIR) are auto-detected but can be overridden:
    config(['testbench-dusk.wordpress.path' => '/custom/wp-path']);
    

Browser Timeout

  • Default timeout is 30 seconds. Adjust in config/testbench-dusk.php:
    'timeout' => 60, // seconds
    

Multi-Site Support

  • Not natively supported. Workaround:
    define('WP_ALLOW_MULTISITE', true);
    require_once ABSPATH . 'wp-admin/includes/ms.php';
    switch_to_blog(2); // Switch to site ID 2
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui