Stan's blog

Selenium Laravel Dusk

Dusk клик по элементу, содержащему текст при тестировании

8 января 2025
Создать /app/Providers/DuskServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Browser;
use Laravel\Dusk\ElementResolver;

class DuskServiceProvider extends ServiceProvider
{
    /**
     * Register Dusk's browser macros.
     */
    public function boot(): void
    {
        ElementResolver::macro("findBySelectorAndText", function ($selector, $text) {

            $elements = [];
            // imitates ElementResolver::findButtonByText
            foreach ($this->all($selector) as $element) {
                if (str_contains($element->getText(), $text)) {
                    $elements[] = $element;
                }
            }
            return $elements;
        });

        // imitates Concerns\InteractsWithMouse::click
        Browser::macro("clickElementWithText", function ($selector, $text) {
            $elements = $this->resolver->findBySelectorAndText($selector, $text);
            foreach ($elements as $one) {
                $one->click();
            }
            return $this;
        });
    }
}
Добавить провайдер в /config/app.php
    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => ServiceProvider::defaultProviders()->merge([
        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\RouteServiceProvider::class,
    ])->toArray(),
Можно пользоваться, но лучше это разместить в tests/DustTestCase.php в public static function prepare(): void, чтобы код выполнялся исключительно при запуске этих тестов.



source