Home  >  Article  >  PHP Framework  >  Beginner's introduction to Laravel Dusk console (code example)

Beginner's introduction to Laravel Dusk console (code example)

不言
不言forward
2019-01-23 10:33:483856browse

This article brings you a beginner's introduction to the Laravel Dusk console (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Laravel Dusk Console is a Laravel extension that provides a beautiful visual panel for your Dusk test suite. It allows you to visualize the various steps involved in running a Dusk test, as well as view DOM snapshots of each step. This is useful for debugging browser tests and figuring out what's going on behind the scenes. At the same time, you can also use your browser's debugging tools to inspect the DOM snapshot.

Beginner's introduction to Laravel Dusk console (code example)

In addition to the visual panel, this extension package also provides the Laravel Dusk test monitor. After you make changes to a Dusk test, the testing process is executed automatically.

This extension pack is strongly inspired by Cypress, the Javascript front-end testing framework.

To view this expansion package, please go to GitHub.

What is Laravel Dusk?

Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. Use Laravel Dusk to write test cases just like on a real browser. For example, when you want to test drag and drop functionality on your website, want to test Vue components or other Javascript related functionality, then you cannot use the Laravels HTTP Test API itself to test.

I think Laravel Dusk is a great package and makes browser testing easier.
Here is a sample test of user registration so you can get an idea of ​​what Laravel Dusk is capable of:

public function test_can_register()
{
    $faker = Factory::create();

    $this->browse(function($browser) use ($faker) {
        $password = $faker->password(9);

        $browser->visit('/register')
            ->assertSee('Register')
            ->type('name', $faker->name)
            ->type('email', $faker->safeEmail)
            ->type('password', $password)
            ->type('password_confirmation', $password)
            ->press('Register')
            ->assertPathIs('/home');
    });
}

To learn more about Laravel Dusk and how to get started with your own browser testing, please Check out the official documentation.

Using the Laravel Dusk Console

Before introducing how the Laravel Dusk console runs internally, let us first take a look at how to install and use this extension package within the Laravel application. .

The following steps assume that you have successfully installed Laravel Dusk according to the official documentation; or even that you have written some Dusk tests.

First, use Composer to install this extension package.

composer require --dev beyondcode/dusk-dashboard

Next, open the DuskTestCase.php generated by Laravel Dusk. You can find this file in the tests directory.

Please be sure to use the test case of this extension package (Test case) as the base class instead of the test case of Laravel Dusk. I'll tell you the inner workings later.

Find this line:

use Laravel\Dusk\TestCase as BaseTestCase;

Replace with the following content:

use BeyondCode\DuskDashboard\Testing\TestCase as BaseTestCase;

Done.

Now you can use the following command to start the Laravel Dusk console and execute your tests.

php artisan dusk:dashboard

An interface similar to this will be displayed in front of you:

Beginner's introduction to Laravel Dusk console (code example)

Start Testing

Just press the "Start Tests" button to run the Laravel Dusk test and observe that you The output of the application when it is tested, and the behavior that occurs.

Subsequently, you will see various events generated by the Dusk test appearing on your console.

Beginners introduction to Laravel Dusk console (code example)

Another way to start Dusk testing is to just edit any test file and save it. The Laravel Dusk console has a built-in file monitor.

Debug Test Steps

You can debug and inspect test actions by clicking on them as they appear in the list. Once clicked, you will see a DOM snapshot representing the state of the HTML page when this action was recorded. If this behavior manipulates the DOM in some way, you can also click the "Before" and "After" buttons to switch between DOM snapshots "before" or "after" the event occurred.

The following is a small example of pressing the "Register" button:

Beginners introduction to Laravel Dusk console (code example)

Checking XHR requests

Sometimes, check when running the test Additional information about the XHR requests that occurred may be useful. For example: there is another button on your website that will perform a GET request to a server.

Dusk Dashboard allows you to log XHR events and display response status and response path.

Beginners introduction to Laravel Dusk console (code example)

XHR request checking is not enabled by default because it requires you to modify browser capabilities.

要启用 XHR 的请求记录,打开你的  DuskTestCase.php ,在文件里,有个 driver 方法,用于设置不同测试操作的 WebDriver。由于此程序包需要对此驱动程序的功能进行一些调整,因此需要使用 $this->enableNetworkLogging 方法调用来封装  DesiredCapabilities 对象。

protected function driver()
{
    $options = (new ChromeOptions)->addArguments([
        '--disable-gpu',
        '--headless',
        '--window-size=1920,1080',
    ]);

    return RemoteWebDriver::create(
        'http://localhost:9515', $this->enableNetworkLogging(
            DesiredCapabilities::chrome()->setCapability(
            ChromeOptions::CAPABILITY, $options
            )
        )
    );
}

通过添加此功能,该程序包将启用记录 XHR 请求和响应信息所需的功能。

工作原理

基本思路十分简单:运行一个 WebSocket 服务,控制台用户连接到这个 WebSocket 服务,接着 PHPUnit 便会将浏览器事件和失败信息发送至所有 WebSocket 连接。

以下是具体的实现方式:

在内部,此扩展包向你的 Laravel 应用内添加了一个名为 StartDashboardCommand 的命令。当此命令被执行时,就会 启动 一个由 Ratchet 开发的 WebSocket 服务。最初我考虑基于我同 Freek 一起开发的 Laravel Websockets 实现此功能,然而随后就毙了这个想法。原因很简单,此扩展包仅能用作开发依赖项,并且我不需要 Pusher 或 Laravel 广播功能,因为广播是通过 PHPUnit 内部实现的。

译者注:Freek 意指 Freek Van der Herten。
另,截至目前,此扩展包也已经发布 v1.0.x 稳定版本。

接下来,我添加两条路由到 WebSocket 服务。

$dashboardRoute = new Route('/dashboard', ['_controller' => new DashboardController()], [], [], null, [], ['GET']);

$this->app->routes->add('dashboard', $dashboardRoute);

$eventRoute = new Route('/events', ['_controller' => new EventController()], [], [], null, [], ['POST']);

$this->app->routes->add('events', $eventRoute);

$dashboardRoute 是一条普通 HTTP 控制器路由,用于输出 Laravel Dusk 控制台的 HTML 视图。

就是这么简单,它只做一件事——返回 HTML 视图:

class DashboardController extends Controller
{
    public function onOpen(ConnectionInterface $connection, RequestInterface $request = null)
    {
        $connection->send(
            str(new Response(
                200,
                ['Content-Type' => 'text/html'],
                file_get_contents(__DIR__.'/../../../resources/views/index.html')
            ))
        );
        $connection->close();
    }
}

$eventRoute 同样是一个 HTTP 路由,但只允许 POST 请求。它被用来在 PHPUnit 和 WebSocket 客户端之间通讯。

同样十分简单,也只做一件事——接收 POST 数据,并广播给所有已连接的 WebSocket 客户端:

class EventController extends Controller
{
    public function onOpen(ConnectionInterface $conn, RequestInterface $request = null)
    {
        try {
            /*
             * 如下即为从 PHPUnit 测试发来的 POST 数据,
             * 发送到已连接的客户端。
             */
            foreach (Socket::$connections as $connection) {
                $connection->send($request->getBody());
            }
            $conn->send(str(new Response(200)));
        } catch (Exception $e) {
            $conn->send(str(new Response(500, [], $e->getMessage())));
        }
        $conn->close();
    }
}

收集浏览器行为

这是整个扩展包最乏味的部分。因为若想收集所有 Laravel Dusk 方法,并将它们广播到 WebSocket 连接,那么必须代理所有的消息再收集它们。

在本扩展包自定义的 TestCase 类里,我们能够重写(override)浏览器实例被创建的过程。那么,此处就是我注入自定义的浏览器(Browser)类的地方。它负责代理现有方法并收集所有行为,同时转发给 WebSocket 连接。

protected function newBrowser($driver)
{
    return new Browser($driver);
}

没什么高端操作。接下来,我原本想直接创建一个新类,传给它 Laravel Dusk 的浏览器类,随后使用 __call 魔术方法代理所有的方法。这能够省下一大堆代码,但也会引出两个问题:

用户无法使用 IDE 自动完成、方法提示功能。

对我来说有点忍不了,我认为这是个非常重要的特性 —— 尤其是对于测试工具来说。开发者并不了解 API 的输入和输出,因此需要 IDE 的提示。

另一个问题是,我不仅仅想在浏览器行为发生后记录 DOM 快照,在某些特定的行为发生前,同样想记录快照。

所以这就是我为何不得不像下面这样,代理所有 Laravel Dusk 方法:

/** @inheritdoc */
public function assertTitle($title)
{
    $this->actionCollector->collect(__FUNCTION__, func_get_args(), $this);

    return parent::assertTitle($title);
}

好了,这样我便能收集并记录各个行为,且依然维持着 IDE 自动完成功能。棒棒哒!

现在你能看到这里的 actionCollector 是 PHPUnit 和 WebSocket 客户端之间的桥梁。它收集获得的信息,并用例如测试名称和 WebSocket POST 推送的端点数据来丰富它:

protected function pushAction(string $name, array $payload)
{
    try {
        $this->client->post('http://127.0.0.1:'.StartDashboardCommand::PORT.'/events', [
            RequestOptions::JSON => [
                'channel' => 'dusk-dashboard',
                'name' => $name,
                'data' => $payload,
            ],
        ]);
    } catch (\Exception $e) {
        // Dusk-Dashboard 服务器可能是关闭的。不必惊慌。
    }
}

它由 try-catch 包裹来保证即使在 Dusk Dashboard 服务器关闭时 Laravel Dusk 也能正常运行。

UI 界面

最后,值得注意的是,此扩展包在它的面板界面里也有很多说道。它由 TailwindCSS 和 Vue 驱动来展示到来的事件以及过滤它们等等。你可以在这 这 查看起始页面的代码。

差不多就这些了。

The above is the detailed content of Beginner's introduction to Laravel Dusk console (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete