Home PHP Framework Laravel Five tips for using Laravel Dusk

Five tips for using Laravel Dusk

May 13, 2020 am 09:30 AM
dusk laravel php

Five tips for using Laravel Dusk

Laravel Dusk 是 Laravel 的一个表达性强、易于使用,且功能强大的浏览器自动化测试工具。通过 Dusk 可以以编程的方式测试 JavaScript 驱动的应用程序。在使用 Dusk 编写测试案例时,我经常遇到一些限制。现在我在本文中将这些情况以及如何克服分享给大家。

1. 填充隐藏字段

在测试某些 JS 组件时 (例如自动完成,日期选择器等) ,可能需要编写动作模拟操作与这些组件交互。犹豫这些组件中的大多数最终都会将值保存到隐藏字段中。那么将值直接填写到隐藏字段中可能更加方便。这可以防止不稳定的测试,并确保我们不测试自己不拥有 / 控制的东西 (第三方组件)。

尽管 Laravel Dusk 没有为我们提供类似 $browser->fillHidden($field, $value) 的方法,但我们可以使用 Dusk Browser Macros 来实现。

//将以下代码添加到 serviceprovider.php 中
Browser::macro('fillHidden', function ($name , $value) {
    $this->script("document.getElementsByName('$name')[0].value = '$value'");
    return $this;
});
// 然后你可以像这样使用
/** @test */
public function fill_hidden_fields()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('https://website.com/form')
                ->type('input.name', $name)
                ->type('input.address', $address)
                ->fillHidden('checkin_date', $date)
                ->click('#Submit')
                ->waitForText('Orders');
    });
}
Copy after login

2. 模拟 HTML 地理位置

我曾经不得不测试一个页面,该页面需要 HTML 网站提供地理位置,以便它可以显示一些结果。没有可用的直接模拟方法,因此我不得不重写 getCurrentPosition 方法,该方法最终将由页面调用。

/** @test */
public function test_geo_location()
{
    $faker = Faker\Factory::create();
    $latitude = $faker->latitude;
    $longitude = $faker->longitude;
    $this->browse(function (Browser $browser) use($latitude, $longitude) {
        $browser->visit(new Homepage)
            ->assertOnPage();
        $browser->driver->executeScript(
            "window.navigator.geolocation.getCurrentPosition = function(onSuccessCallback) {
                var position = {
                    'coords': { 'latitude': {$latitude}, 'longitude': {$longitude} }
                };
                onSuccessCallback(position);
            }"
        );
        $browser->click('#geolocate-button')
                ->assertSee('Longitude: $longitude')
                ->assertSee('Latitude: Latitude')
    });
}
Copy after login

3. 使用 XPath 选择器

有时,我会遇到无法使用 CSS 选择器来定位元素的情况。这些通常发生在动态表格中,或者在我无法修改的第三方 js 组件中。但是,Laravel Dusk 不直接支持 XPath 选择器,并且经常需要访问基础 WebDriver 实例。

$browser->driver->findElement(
WebDriverBy::xpath("//table[@class='x-grid3-row-table']/tbody/tr/td/div/a[contains(text(),'$value')]")
)->click();
Copy after login

这种方法的唯一问题就是 [问题不大] 可能会终端 $browser 链式调用.

4. 整页截屏

Laravel dusks 为我们提供了失败测试的屏幕截图,这对于了解测试失败的原因非常有帮助。但是,有时错误或有问题的元素可能在屏幕显示区域以外。

要在 Laravel Dusk 中创建完整的屏幕截图,我们必须在我们的 tests \ DuskTestCase.php 中创建一个 captureFailuresFor() 方法,它将覆盖最初在 Laravel\Dusk\Concerns\ProvidesBrowser 中定义的一个方法。

protected function captureFailuresFor($browsers)
{
    $browsers->each(function (Browser $browser, $key) {
        $body = $browser->driver->findElement(WebDriverBy::tagName('body'));
        if (!empty($body)) {
            $currentSize = $body->getSize();
            $size = new WebDriverDimension($currentSize->getWidth(), $currentSize->getHeight());
            $browser->driver->manage()->window()->setSize($size);
        }
        $name = str_replace('\\', '_', get_class($this)).'_'.$this->getName(false);
        $browser->screenshot('failure-'.$name.'-'.$key);
    });
}
Copy after login

现在,无论何时我们调用 $browser->screenshot('$shotname') ,发生错误时我们都将获得完整的屏幕截图

5. 访问浏览器错误日志

这个没什么问题,只是我发现的一些有趣的东西。我们可以通过调用 $browser->driver->manage()->getLog(‘browser’) 来访问浏览器控制台日志。

这将在浏览器的控制台中返回一系列日志。例如,对于页面上没有 javascript 错误的测试而言,它可能很有用。

@test
public function no_browser_errors()
{
    $this->browse(function ($browser) {
        $this->assertEmpty($browser->driver->manage()->getLog('browser'));
    });
}
Copy after login

但是请注意,它不包含 console.log 调用的输出

结论

感谢您阅读本文,希望您有所收获。

感谢阅读

推荐教程:《Laravel教程》《PHP教程

The above is the detailed content of Five tips for using Laravel Dusk. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles