docker-compose.yml
本指南運行環境系 MacBook 上的 Docker 內,相關容器配置如下:
1# docker-compose.yml
2version: '3'
3services:
4 mysql:
5 image: mariadb:10.2
6 restart: always
7 volumes:
8 - '~/Documents/Datas/laravel/mysql:/var/lib/mysql'
9 ports:
10 - '127.0.0.1:23306:3306'
11 environment:
12 MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
13 MYSQL_DATABASE: 'puppy'
14 laravel:
15 image: ycheung/laravel-dev
16 restart: always
17 ports:
18 - '8081:80'
19 - '9001:9001'
20 volumes:
21 - '~/Documents/laravel:/var/www/html'
22 depends_on:
23 - mysql
24 - mailhog
25 mailhog:
26 image: mailhog/mailhog
27 ports:
28 - "1025:1025"
29 - "8025:8025"
30 selenium-hub:
31 image: selenium/hub
32 container_name: selenium-hub
33 ports:
34 - "4444:4444"
35 chrome:
36 image: selenium/node-chrome
37 volumes:
38 - '/dev/shm:/dev/shm'
39 depends_on:
40 - selenium-hub
41 environment:
42 - HUB_HOST=selenium-hub
43 - HUB_PORT=4444
44 - JAVA_OPTS=-Dwebdriver.chrome.whitelistedIps=
安裝 Laravel Dusk
1composer require --dev laravel/dusk
執行安裝腳本
執行安裝腳本,生成測試目錄 tests/Browser 和示例測試文件
1php artisan dusk:install
編輯 .env
編輯 .env 文件,設置 APP_URL=http://laravel ,URL地址是服務名(service name)。
編輯 DuskTestCase.php
編輯 tests/DuskTestCase.php 文件, selenium_server_url地址是 http://selenium-hub:4444/wd/hub
錯誤解決
如果遇到錯誤 Facebook\WebDriver\Exception\UnknownErrorException: Session [xxx] was terminated due to BROWSER_TIMEOUT
,將 connection_timeout_in_ms
和
request_timeout_in_ms
的值改大些,比如 9000
。(optional)
1// tests/DuskTestCase.php
2
3<?php
4
5namespace Tests;
6
7use Facebook\WebDriver\Chrome\ChromeOptions;
8use Facebook\WebDriver\Remote\DesiredCapabilities;
9use Facebook\WebDriver\Remote\RemoteWebDriver;
10use Laravel\Dusk\TestCase as BaseTestCase;
11
12abstract class DuskTestCase extends BaseTestCase
13{
14 use CreatesApplication;
15
16 /**
17 * Prepare for Dusk test execution.
18 *
19 * @beforeClass
20 * @return void
21 */
22 public static function prepare()
23 {
24 if (!static::runningInSail()) {
25 static::startChromeDriver();
26 }
27 }
28
29 /**
30 * Create the RemoteWebDriver instance.
31 *
32 * @return \Facebook\WebDriver\Remote\RemoteWebDriver
33 */
34 protected function driver()
35 {
36 $options = (new ChromeOptions)->addArguments(collect([
37 '--window-size=1920,1080',
38 ])->unless($this->hasHeadlessDisabled(), function ($items) {
39 return $items->merge([
40 '--disable-gpu',
41 '--headless',
42 ]);
43 })->all());
44
45 return RemoteWebDriver::create(
46 $_ENV['DUSK_DRIVER_URL'] ?? 'http://selenium-hub:4444/wd/hub',
47 DesiredCapabilities::chrome()->setCapability(
48 ChromeOptions::CAPABILITY, $options
49 ), 90000, 90000
50 );
51 }
52
53 /**
54 * Determine whether the Dusk command has disabled headless mode.
55 *
56 * @return bool
57 */
58 protected function hasHeadlessDisabled()
59 {
60 return isset($_SERVER['DUSK_HEADLESS_DISABLED']) ||
61 isset($_ENV['DUSK_HEADLESS_DISABLED']);
62 }
運行示例測試任務
1php artisan dusk