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'); }); }
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') }); }
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();
这种方法的唯一问题就是 [问题不大] 可能会终端 $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); }); }
现在,无论何时我们调用 $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')); }); }
但是请注意,它不包含 console.log 调用的输出
结论
感谢您阅读本文,希望您有所收获。
感谢阅读
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!

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment