Coder Social home page Coder Social logo

laravel / dusk Goto Github PK

View Code? Open in Web Editor NEW
1.8K 1.8K 317.0 105.34 MB

Laravel Dusk provides simple end-to-end testing and browser automation.

Home Page: https://laravel.com/docs/dusk

License: MIT License

PHP 99.85% Blade 0.15%
laravel testing webdriver

dusk's Introduction

Laravel Logo

Build Status Total Downloads Latest Stable Version License

About Laravel

Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:

Laravel is accessible, powerful, and provides tools required for large, robust applications.

Learning Laravel

Laravel has the most extensive and thorough documentation and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.

You may also try the Laravel Bootcamp, where you will be guided through building a modern Laravel application from scratch.

If you don't feel like reading, Laracasts can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.

Laravel Sponsors

We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel Partners program.

Premium Partners

Contributing

Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the Laravel documentation.

Code of Conduct

In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.

Security Vulnerabilities

If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [email protected]. All security vulnerabilities will be promptly addressed.

License

The Laravel framework is open-sourced software licensed under the MIT license.

dusk's People

Contributors

aand18 avatar bbashy avatar browner12 avatar calebporzio avatar carusogabriel avatar crynobone avatar dasred avatar deleugpn avatar derekmd avatar dmitryuk avatar driesvints avatar duncan3dc avatar hivokas avatar inxilpro avatar janiaje avatar mbardelmeijer avatar mnabialek avatar nesk avatar nunomaduro avatar ockle avatar sileence avatar sjorso avatar splateric avatar spyric avatar staudenmeir avatar taylorotwell avatar themsaid avatar u01jmg3 avatar vinkla avatar ziadoz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dusk's Issues

Can't run dusk tests on ubuntu 16.04

I am trying laravel dusk on a fresh installation laravel 5.4.x-dev
This is what I get when I run php artisan dusk

PHPUnit 5.7.5 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.0.13-0ubuntu0.16.04.1 with Xdebug 2.4.0
Configuration: /var/www/html/dusk/phpunit.dusk.xml

E                                                                   1 / 1 (100%)

Time: 2.5 minutes, Memory: 10.00MB

There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"desiredCapabilities":{"browserName":"chrome","platform":"ANY"}}

Operation timed out after 30000 milliseconds with 0 bytes received

/var/www/html/dusk/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:287
/var/www/html/dusk/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:121
/var/www/html/dusk/tests/DuskTestCase.php:32
/var/www/html/dusk/vendor/laravel/dusk/src/TestCase.php:176
/var/www/html/dusk/vendor/laravel/framework/src/Illuminate/Support/helpers.php:639
/var/www/html/dusk/vendor/laravel/dusk/src/TestCase.php:177
/var/www/html/dusk/vendor/laravel/dusk/src/TestCase.php:107
/var/www/html/dusk/vendor/laravel/dusk/src/TestCase.php:81
/var/www/html/dusk/tests/Browser/ExampleTest.php:21

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

jQuery requirement

Hello,

The following line:

var link = $("{$selector}");

in Laravel\Dusk\Concerns\MakesAssertions's seeLink() function is problematic for projects that do not use jQuery as developers will be presented with Facebook\WebDriver\Exception\UnknownServerException: unknown error: $ is not defined.

Would it be possible to remove the jQuery dependency with native javascript?

[RFC] Additional options for dusk:page command on creating test class

Overview

A short-cut in creating DuskTestCase from a Dusk\Page.

Proposed:
php artisan dusk:page --test <name>
php artisan dusk:page -t <name> (using alias)

Example:
php artisan dusk:page -t CheckoutPage
Will create the following files CheckoutPage.php and CheckoutPageTest.php

Sample Output:

tests/Browser
โ”œโ”€โ”€ CheckoutPageTest.php
โ”œโ”€โ”€ Pages
โ”‚ย ย  โ”œโ”€โ”€ CheckoutPage.php
โ”‚ย ย  โ””โ”€โ”€ Page.php
โ””โ”€โ”€ screenshots

Page Scaffolding:

To have a default value on the URI, additional option is used:

Proposed:
php artisan dusk:page --uri=<uri> <name>

Example:
php artisan dusk:page --uri=/checkout CheckoutPage

   /**
     * Get the URL for the page.
     *
     * @return string
     */
    public function url()
    {
        return '/checkout';
    }

Summary:

Using the following command: php artisan dusk:page --uri=/checkout --test CheckoutPage

  • Will generate two (2) files: CheckoutPage.php and CheckoutPageTest.php
  • Will return /checkout for Page::url() method

Cannot run test on Homestead/Docker

There are 2 problems with this (I personally test it in Docker):

  1. Tests won't run without running extra commands at all (missing libs etc. so before running tests you need to run those magic commands) or you get :

Failed to connect to localhost port 9515: Connection refused

  1. Even if you run multiple commands it still might not work. What I'm finally getting is:
  1. Tests\Browser\ExampleTest::testBasicExample
    Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"desiredCapabilities":{"browserName":"chrome","platform":"ANY"}}

Operation timed out after 30000 milliseconds with 0 bytes received

/usr/share/nginx/html/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:287
/usr/share/nginx/html/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:121
/usr/share/nginx/html/tests/DuskTestCase.php:32
/usr/share/nginx/html/vendor/laravel/dusk/src/TestCase.php:180
/usr/share/nginx/html/vendor/laravel/framework/src/Illuminate/Support/helpers.php:639
/usr/share/nginx/html/vendor/laravel/dusk/src/TestCase.php:181
/usr/share/nginx/html/vendor/laravel/dusk/src/TestCase.php:111
/usr/share/nginx/html/vendor/laravel/dusk/src/TestCase.php:85
/usr/share/nginx/html/tests/Browser/ExampleTest.php:20

The commands I've run to get to error in step 2 were:

wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub |  apt-key add -
sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'
apt-get update && apt-get install -y google-chrome-stable
apt-get install -y xvfb

dd('here') ?

Are you sure you want to leave that dd('here') in the code that should load JQUery?

See: 193e070

Screenshots folder hardcoded in several places

Hi,

I don't want to have a Browser/screenshots into my tests directory. I already have a folder for my artifacts elsewhere. But I notice that the call to base_path('tests/Browser/screenshots') is hardcoded in several places

->in(base_path('tests/Browser/screenshots'))
Browser::$storeScreenshotsAt = base_path('tests/Browser/screenshots');

Is it possible to create a config file for Dusk allowing to change this parameter? I manage to fix the TestCase with:

    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     * @return void
     */
    public static function prepare()
    {
        Browser::$storeScreenshotsAt = storage_path('tests/screenshots');

        static::startChromeDriver();
    }

But I can't find a way to fix the DuskCommand classโ€ฆ
I can make a PR if wanted.

Thanks,

Issues running tests on Mac/Valet

While trying out Dusk it looks like its trying to launch my Chrome browser and not the Chrome driver

Environment

  • Mac OS X
  • Laravel Valet 2.0.3
  • PHP 7.1.0
  • Fresh install of Laravel 5.4 (current dev-master)
  • Default (dusk:install) test only

Test run

php artisan dusk
PHPUnit 5.7.5 by Sebastian Bergmann and contributors.

E         1 / 1 (100%)

Time: 2.85 seconds, Memory: 10.00MB

There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\UnknownServerException: unknown error: Chrome version must be >= 54.0.2840.0
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.12.1 x86_64)

./vendor/facebook/webdriver/lib/Exception/WebDriverException.php:114
./vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:321
./vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:121
./tests/DuskTestCase.php:32
./vendor/laravel/dusk/src/TestCase.php:178
./vendor/laravel/framework/src/Illuminate/Support/helpers.php:639
./vendor/laravel/dusk/src/TestCase.php:179
./vendor/laravel/dusk/src/TestCase.php:109
./vendor/laravel/dusk/src/TestCase.php:83
./tests/Browser/ExampleTest.php:21

Compatibility with Centos 6?

I've been trying to get dusk to work on my Docker setup which uses Centos 6.8 but seem to run into different issues. Unless I understand this wrong, I need Chrome installed to get chromedriver to work correct? Well I did just that (using https://chrome.richardlloyd.org.uk/ since newer versions Google Chrome do not support RHEL 6 anymore) and after trying to run the chromedriver-linux bin, I am met with library issues ('GLIBCXX_3.4.15' not found, 'CXXABI_1.3.5' not found, 'GLIBCXX_3.4.14' not found). I then read that I could get chromedriver to use the libraries from the chrome install I just performed (export LD_LIBRARY_PATH=/opt/google/chrome/lib). This does seem to make it work now

./vendor/laravel/dusk/bin/chromedriver-linux
Starting ChromeDriver 2.25.426924 (649f9b868f6783ec9de71c123212b908bf3b232e) on port 9515
Only local connections are allowed.

Unfortunately, trying to run ./artisan dusk -vvv gives me the following

PHPUnit 5.7.9 by Sebastian Bergmann and contributors.

Runtime:       PHP 5.6.30
Configuration: /var/www/html/mysite/phpunit.dusk.xml

and it stays there for a while before crashing with an error stating that the operation timed out. Is there anything else I'm missing to get this working?

[Feature Request] allow disabling of web security

I have a legacy screen scraper that needs --disable-web-security passing to the WebDriver to allow my Jquery snippets to manipulate elements in Cross Origin iframes.

I foresee dusk as a great way to test my App, but also as a way to integrate my external scraper into one codebase. Being able to specify that the Chrome instance that is instantiated disregards some brower security rules would be very useful.

Facebook\WebDriver\Exception\NoSuchDriverException: no such session

Hi,

I'm starting to scaffold a suite of browser tests for a project, however when I run the full suite via php artisan dusk 90% of the tests fail to due what seems like a race condition.

10) Tests\Browser\RegisterTest::testPublicCanRegister
Facebook\WebDriver\Exception\NoSuchDriverException: no such session
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.12.3 x86_64)

/Users/owen/Sites/footy-finance/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:100
/Users/owen/Sites/footy-finance/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:321
/Users/owen/Sites/footy-finance/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:597
/Users/owen/Sites/footy-finance/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:373
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/Browser.php:186
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/TestCase.php:143
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Support/Collection.php:244
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/TestCase.php:144
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/TestCase.php:90
/Users/owen/Sites/footy-finance/tests/Browser/RegisterTest.php:65

If I run the tests class by class like php artisan dusk tests/Browser/RegisterTest.php they always work.

It just seems when they're all together they expect your computer to be consistently fast and be able to spin up a chrome instance and load the page before the timeout.

Is there anyway we can make it so it slows down/waits a little longer before trying to run the tests?

Dusk suddenly always fails with "unknown command"

After upgrading my application to 5.4, I began converting all my integration tests to Dusk browser tests.

This was going very well for the first few tests, when suddenly all of my tests started failing, with this screenshot saved in the screenshots folder (simply says unkown command:):
failure-testaccountnormaluser-0

Now, even on a totally fresh Laravel install, that is what every test gives me every time.

I don't even know where to begin to fix this, php artisan dusk -vvv does not give any information. The browser simply will not load anything anymore.

Can anyone give me guidance on how to debug this?

Integrate cloud testing

Hey,

any plans to integrate

  • Saucelabs
  • Testingbot
  • Browserstack
  • โ€ฆ

as environment where a Dusk task can run?

In Codeception integrations are available

Can't type() into date input fields

I'm trying to fill in a form that has a date field in it. Note that this is a plain HTML5 date field, no JS datepickers or anything to complicate matters, e.g.

<input class="form-control" name="walk_date" type="date" id="walk_date">

Trying to input into that field in a dusk test using type() fails. Sample code:

$browser->type('walk_date', '01-02-2017')

Results in the following exception:

Facebook\WebDriver\Exception\InvalidElementStateException: invalid element state: Element must be user-editable in order to clear it.
  (Session info: chrome=55.0.2883.95)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.12.3 x86_64)

/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:112
/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:321
/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:597
/vendor/facebook/webdriver/lib/Remote/RemoteExecuteMethod.php:40
/vendor/facebook/webdriver/lib/Remote/RemoteWebElement.php:66
/vendor/laravel/dusk/src/Concerns/InteractsWithElements.php:154
/tests/MhbHelpers.php:21

I'm currently working around this using keys(), but it seems like this should be fixed - or at least documented.

Example workaround

 $browser 
     ->keys('#walk_date', '{backspace}')
     ->keys('#walk_date', $walkDate->format('d'))
     ->keys('#walk_date', '{backspace}')
     ->keys('#walk_date', $walkDate->format('m'))
     ->keys('#walk_date', '{backspace}')
     ->keys('#walk_date', $walkDate->format('Y'))

[Request] Proposal for Browser class

All of the stubs reference the Browser class at Laravel\Dusk\Browser. My proposal is that a Browser class is installed within the tests that extends Laravel\Dusk\Browser. Not exactly sure the best/most logical place for this file, perhaps tests/Dusk/Browser.php.

The reason for this is that I have created some custom methods on the browser like loginAsUser() and loginAsAdmin(). I also set those users into the object and are made available as $browser->user. This is just part of my use case, but I can see the potential for people needing this kind of flexibility on their browser object.

If you would like, I can create a PR with the necessary code to accomplish this feature.

Adding assertHasOption and assertHasOptions

It would be very nice to have an assert if the dropdown menu contains given value(s). For example:

->assertHasOption('@countries', 'Finland');
->assertHasOptions('@countries', ['Finland', 'Sweden]);

I tried to look to the Facebook Webdriver API to make a PR but it went little bit over my head. Maybe somebody more capable would like to implement this?

DatabaseMigrations trait doesn't work when using an in-memory SQLite database

I would like to know how tet up Laravel 5.4 with Dusk using phpunit.xml, .env.dusk.local, and an sqlite in-memory database as what I have so far doesn't work. It does work with a MySQL database though.

I can run the tests, but I get an error: "No such table: users"

  • I have created a new Laravel 5.4 project
  • Installed Dusk and added the Service Provider
  • I'm using the test from the laravel docs that tests authentication. It already includes the DatabaseMigrations trait
  • I can run the tests, and the first one works (navigating to the /login route) but the second where it tried to log in fails.

I have added a .env.dusk.local which contains

APP_ENV=local
APP_KEY=RANDOM_STRING_HERE
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://laravel54.dev

DB_CONNECTION=sqlite
DB_DATABASE=':memory:' // I've also tried just :memory: and also adding these details to the config/database.php file but to no avail

This is the test I am running (directly from the docs)

<?php

namespace Tests\Browser;

use App\User;
use Tests\DuskTestCase;
use Laravel\Dusk\Chrome;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class LoginTest extends DuskTestCase
{
    use DatabaseMigrations;

    public function test_login_page()
    {
        $user = factory(User::class)->create();

        $this->browse(function ($browser) use ($user) {
            $browser->visit('/login')
                ->type('email', $user->email)
                ->type('password', 'secret')
                ->press('Sign in')
                ->assertPathIs('/home');
        });
    }
}

Ref: Question on StackOverflow

Ref: Question on Laracasts

clickLink does not escape quotes

Code like $browser->clickLink($user->name) causes error if name contains quotes (something like Bert O'Keefe)

Full error output:

1) Tests\Browser\LayoutTest::testBasicNavigation
Facebook\WebDriver\Exception\UnknownServerException: unknown error: Cannot read property 'click' of undefined
  (Session info: chrome=54.0.2840.100)
  (Driver info: chromedriver=2.25.426924 (649f9b868f6783ec9de71c123212b908bf3b232e),platform=Linux 4.4.0-59-generic x86_64)

/home/rmoiseev/PhpstormProjects/app/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:114
/home/rmoiseev/PhpstormProjects/app/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:321
/home/rmoiseev/PhpstormProjects/app/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:597
/home/rmoiseev/PhpstormProjects/app/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:335
/home/rmoiseev/PhpstormProjects/app/vendor/laravel/dusk/src/Concerns/InteractsWithElements.php:60
/home/rmoiseev/PhpstormProjects/app/tests/Browser/LayoutTest.php:36
/home/rmoiseev/PhpstormProjects/app/vendor/laravel/dusk/src/TestCase.php:88
/home/rmoiseev/PhpstormProjects/app/tests/Browser/LayoutTest.php:47

Everything works fine If link text does not contain quotes.

ReflectionException: Class config does not exist

Hi guys, recently upgraded a 5.3 project to 5.4 and all seemed good.

Today I started to implement Dusk however had hit an issue when running the example test

โ˜  footy-finance [5.4] โšก php artisan dusk
PHPUnit 6.0.0 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 162 ms, Memory: 6.00MB

There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
ReflectionException: Class config does not exist

/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Container/Container.php:681
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Container/Container.php:565
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:105
/Users/owen/Sites/footy-finance/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:263
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/TestCase.php:203
/Users/owen/Sites/footy-finance/vendor/laravel/dusk/src/TestCase.php:40

I've had a look at line 40 of TestCase.php and its

public function baseUrl()
{
    return config('app.url');
}

So it does look like something to do with the global config helper anybody have any ideas?

I'm running

  • PHP 7.0.14
  • Laravel/Framework 5.4.8
  • Laravel/Dusk 1.0.5
  • PHPUnit 6.0

The full composer.lock can be seen https://gist.github.com/OwenMelbz/c05172b33f6eb4483e37a56469b53722

Fingers crossed you guys have some ideas!

Cheers :)

Laravel 5.3 support

composer.json declares Laravel 5.3 support

But problem is that laravel/framework: 5.3 requires symfony/console: 3.1 and laravel/dusk requires symfony/console: 3.2

Unable to Run Tests on a dynamic URL

Just watched @JeffreyWay's What's new in Laravel 5.4 : E09 and everything worked out till i ran
php artisan dusk ๐Ÿ˜›

I am bit confused @ 1:42 where Jeffrey sets 'url' value.

'domain' => env('APP_DOMAIN', 'me.com'),
'url' => 'https://'.env('APP_DOMAIN'),

Previous phpunit tests had all sorts of database connectivity where user logs in and is redirected to a view etc.

screen shot 2017-02-01 at 2 29 57 pm

Dusk env file not being loaded correctly

I have the following two files: .env and .env.dusk.local

.env:

APP_ENV="local"
APP_KEY=base64:358E4UyIq+Zbg+H+Pm03dYA2B/vz3ViPJ+U48ikg6qE=
APP_DEBUG=true
APP_LOG_LEVEL="debug"
APP_URL="http://localhost"

DB_CONNECTION="mysql"
DB_HOST="127.0.0.1"
DB_DATABASE="homestead"
DB_USERNAME="homestead"
DB_PASSWORD="secret"

CACHE_DRIVER="redis"
SESSION_DRIVER="redis"
QUEUE_DRIVER="sync"

.env.dusk.local

APP_ENV="local"
APP_KEY=base64:358E4UyIq+Zbg+H+Pm03dYA2B/vz3ViPJ+U48ikg6qE=
APP_DEBUG=true
APP_LOG_LEVEL="debug"
APP_URL="http://localhost"

DB_CONNECTION="sqlite"

CACHE_DRIVER="file"
SESSION_DRIVER="file"
QUEUE_DRIVER="sync"

But when I run php artisan dusk I get errors about the sqlite database not existing.
Illuminate\Database\QueryException: Database (homestead) does not exist. (SQL: select * from sqlite_master where type = 'table' and name = migrations)

So, I suspect that the env files are not correctly being copied and swapped into place. It seems they are simple being merged together, which is causing issues for tests not working.

I am currently using this on Manjaro Linux, and have not tried it on any other OS.

In windows 10, does laravel dusk always open the 'chrome' browser?

Just a quick question, in windows 10, does laravel dusk always open the 'chrome' browser? I see the dusk tests like if i was using the browser. i see the input getting filled in, with username, password, for instance. Isn't it supposed to do all this stuff 'hidden' from view, just expecting the console output? It gets worse, when i use 2 browser tests, the computer almost comes to a halt. very very slow, like 30 seconds for a simple login test.

Explicit environment whitelisting

Not sure if this is the best place for this, but I wanted to make the suggestion that the Dusk login route only be exposed for specific environments.

Whilst the docs do point out that you should only include the service provider in local or testing, I wonder whether it would be better if Service Provider itself was checking this as well. To ensure full flexibility, there could be a white listing environment variable so if people wanted to expose it in other environments as well they could.

My reasoning for this is that it would be very simple for someone to skim read the docs and not pick up on this detail. If they simply included the service provider as standard, this would be something of a security flaw.

Something like:

class DuskServiceProvider extends ServiceProvider
{

    public function boot()
    {
        if (in_array(env('APP_ENV'), array_merge(['local','testing'], explode(',', env('DUSK_WHITELIST', ''))), false)) {
            Route::get('/_dusk/login/{userId}', [
                'middleware' => 'web',
                'uses' => 'Laravel\Dusk\Http\Controllers\LoginController@login'
            ]);

            $this->app->booted(function () {
                $this->makeLogoutAccessibleViaGet();
            });
        }
    }

[Features Request] Path assertions

Hi,

Is it possible to add some additional assertions, related to the current path?
Here some suggestions:

// Assert the current path doesn't match the given path.
$browser->assertPathIsNot('/bad-url');

// Assert the current path matches the given regular expression.
// See: http://codeception.com/docs/modules/WebDriver#seeCurrentUrlMatches
$browser->assertPathMatches($regex);

// Assert the current path doesn't match the given regular expression.
// See: http://codeception.com/docs/modules/WebDriver#dontSeeCurrentUrlMatches
$browser->assertPathDoesntMatch($regex);

Cheers,
Tortue Torche

Other selectors than css? xpath?

Might it be possible to support different selectors than the cssSelector?
The webdriver also supports xpath selectors.
It would be great if functions like text() will support xpath also.

I've played a little bit with the Dusk code and added a parameter to the text() function and it seems to be very easy. But i'm not sure if this is the best way.
Dusk might also detect xpath by itself (by search for // at the beginning, for example).

What do you think?

Page Shorthand Selectors not working (or I could not understand how to use it)

I created a page (test) and added the following shorthand selectors:

 public function elements()
    {
        return [
            '@loginButton' => '#login-submit',
            '@username' => '#login-input-email',
            '@password' => '#login-input-password',
            '@forgot-password' => '.login__bottom-form-link',
            '@logo' => '.login__logo-image'
        ];
    }

in the assert method of the page I tried to do the following:

 public function assert(Browser $browser)
    {
        $browser->assertPathIs($this->url());
        $browser->waitFor('@loginButton')
            ->assertSeeIn('@loginButton', 'Sign In');
    }

and it's not working as I expected. it doesn't find the selectors.
however, if I change the shorthand to this form:

 public function assert(Browser $browser)
    {
        $browser->assertPathIs($this->url());
        $browser->waitFor('#login-submit')
            ->assertSeeIn('#login-submit', 'Sign In');
    }

it works as expected.

So what am I doing wrong here?

Exit code on test failure

Would it be possible for the dusk command to forward the exit code emitted by PHPUnit?

Right now Dusk seem to always exit with an exit code of zero indicating no errors even if one or more tests failed. For CI, like Travis, it would be awesome to have the exit code from PHPUnit forwarded so failures can be caught.

Unused $expiration variable in addCookie

I think this function in /src/Concerns/InteractsWithCookies.php is not doing anything with the $expiration variable

    public function addCookie($name, $value, $expiration, array $options = [], $encrypt = true)
    {
        if ($encrypt) {
            $value = encrypt($value);
        }
        if ($expiration instanceof DateTimeInterface) {
            $expiration = $expiration->getTimestamp();
        }
        $this->driver->manage()->addCookie(
            array_merge($options, compact('name', 'value'))
        );
        return $this;
    }

Should it be passed in the compact call?

compact('name', 'value', 'expiration')

I think, based on the source of the Facebook/Webdriver, it should be called $expiry
source: lib/WebDriverOptions.php

    /**
     * Add a specific cookie.
     *
     * Here are the valid attributes of a cookie array.
     *  'name'    : string The name of the cookie; may not be null or an empty string.
     *  'value'   : string The cookie value; may not be null.
     *  'path'    : string OPTIONAL The path the cookie is visible to. Defaults to "/" if omitted.
     *  'domain'  : string OPTIONAL The domain the cookie is visible to. Defaults to the current browsing context's
     *                     document's URL domain if omitted.
     *  'secure'  : bool   OPTIONAL Whether this cookie requires a secure connection (https). Defaults to false if
     *                     omitted.
     *  'httpOnly': bool   OPTIONAL Whether the cookie is an HTTP only cookie. Defaults to false if omitted.
     *  'expiry'  : int    OPTIONAL The cookie's expiration date, specified in seconds since Unix Epoch.
     *
     * @see https://w3c.github.io/webdriver/webdriver-spec.html#cookies
     * @param array $cookie An array with key as the attributes mentioned above.
     * @return WebDriverOptions The current instance.
     */
    public function addCookie(array $cookie)
    {
        $this->validate($cookie);
        $this->executor->execute(
            DriverCommand::ADD_COOKIE,
            ['cookie' => $cookie]
        );

        return $this;
    }

Dusk tests fail when using ./vendor/bin/phpunit tests/

Problem overview: phpunit and Dusk tests cannot run parallel

The scenario: ./vendor/bin/phpunit tests/ triggers all tests (including Dusk). However the Dusk specific tests fail. If I execute php artisan dusk they pass.

It's worth pointing out that you can run tests without Dusk by running ./vendor/bin/phpunit

Basic Install Chromedriver Does Not Start (Windows)

Did a fresh install of laravel and the ran composer require laravel/dusk, following the scaffolding and the chrome driver doesn't work. Am I supposed to be running something outside of running the tests that is meant for dusk to connect to?

`
$ ./vendor/bin/phpunit -c phpunit.dusk.xml
PHPUnit 5.7.7 by Sebastian Bergmann and contributors.

E                                                                  1 / 1 (100%)

Time: 9.41 seconds, Memory: 8.00MB

There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session     with params: {"desiredCapabilities":{"browserName":"chrome","platform":"ANY"}}

Failed to connect to localhost port 9515: Connection refused

(app_path)\vendor\facebook\webdriver\lib\Remote\HttpCommandExecutor.php:287
(app_path)\vendor\facebook\webdriver\lib\Remote\RemoteWebDriver.php:121
(app_path)\tests\DuskTestCase.php:32
(app_path)\vendor\laravel\dusk\src\TestCase.php:180
(app_path)\vendor\laravel\framework\src\Illuminate\Support\helpers.php:639
(app_path)\vendor\laravel\dusk\src\TestCase.php:181
(app_path)\vendor\laravel\dusk\src\TestCase.php:111
(app_path)\vendor\laravel\dusk\src\TestCase.php:85
(app_path)\tests\Browser\ExampleTest.php:21

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

`

An invalid or illegal selector was specified... Problem with form arrays?

When running Dusk tests the following exception is thrown:

Facebook\WebDriver\Exception\InvalidSelectorException: invalid selector: An invalid or illegal selector was specified

This appears to be connected with the use of arrays in HTML forms:

$browser->press('Add Variable')
               ->type('variables[name]', 'Force')      // line 26

Full Stack Trace

1) Tests\Browser\QuestionTemplateTest::create_a_new_question_template
Facebook\WebDriver\Exception\InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=55.0.2883.87)
  (Driver info: chromedriver=2.25.426924 (649f9b868f6783ec9de71c123212b908bf3b232e),platform=Linux 4.4.0-53-generic x86_64)

/home/simon/Code/thephysics.guide/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:152
/home/simon/Code/thephysics.guide/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:321
/home/simon/Code/###/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:597
/home/simon/Code/###/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:189
/home/simon/Code/###/vendor/laravel/dusk/src/ElementResolver.php:293
/home/simon/Code/###/vendor/laravel/dusk/src/ElementResolver.php:275
/home/simon/Code/###/vendor/laravel/dusk/src/ElementResolver.php:88
/home/simon/Code/###/vendor/laravel/dusk/src/Concerns/InteractsWithElements.php:154
/home/simon/Code/###/tests/Browser/QuestionTemplateTest.php:26
/home/simon/Code/###/vendor/laravel/dusk/src/TestCase.php:88
/home/simon/Code/###/tests/Browser/QuestionTemplateTest.php:42

Change extension of stubs

Currently dusk stubs have the .php extension which causes PhpStorm(maybe other IDEs) to warn about multiple class definitions for eg. DuskTestCase.
Can we change the extension to .stub, like for generator commands?

This will require changes in Laravel\Dusk\Console\InstallCommand::handle:
Before:

copy(__DIR__.'/../../stubs/ExampleTest.php', base_path('tests/Browser/ExampleTest.php'));
copy(__DIR__.'/../../stubs/HomePage.php', base_path('tests/Browser/Pages/HomePage.php'));
copy(__DIR__.'/../../stubs/DuskTestCase.php', base_path('tests/DuskTestCase.php'));
copy(__DIR__.'/../../stubs/Page.php', base_path('tests/Browser/Pages/Page.php'));

After:

copy(__DIR__.'/../../stubs/ExampleTest.stub', base_path('tests/Browser/ExampleTest.php'));
copy(__DIR__.'/../../stubs/HomePage.stub', base_path('tests/Browser/Pages/HomePage.php'));
copy(__DIR__.'/../../stubs/DuskTestCase.stub', base_path('tests/DuskTestCase.php'));
copy(__DIR__.'/../../stubs/Page.stub', base_path('tests/Browser/Pages/Page.php'));

What do you think?

Cannot click on multiple checkboxes with the same name field

I have a rather lengthy form that I am trying to test with Dusk and I cannot figure out how to check a box that is part of an array of checkboxes. For instance, take this...

@foreach($physicalNeeds as $item)
    <div class="checkbox">
        <label>
            <input type="checkbox" value="{{ $item->id }}" name="physical_needs[]">
                {{ ucfirst($item->name) }}
        </label>
    </div>
@endforeach

Now, for my test, I have...

->check('physical_needs', 'Water')
->check('physical_needs', 'Meals')

Before I do that, I fill out a number of other fields so I know it's working in that regard and is strictly an issue with the checkboxes. For instance, a couple lines up, I do this and it is working:

->check('has_power')

The error that I am getting is this:

Facebook\WebDriver\Exception\InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=55.0.2883.95)

Unfortunately, the docs do not specify how to handle this. If someone can point me in the right direction, I would love to fix my issue, but also update the docs so that others know how to do this.

Problem running dusk on Homestead

Hello,

So I just installed a new Laravel 5.4 project and thought I'd give Dusk a try..

Followed the installation steps in the documentation:

  1. Ran composer require laravel/dusk
  2. Updated AppServiceProvider.php
  3. Ran php artisan dusk:install

But when I run php artisan dusk I get the following output:

dir=$(d=${0%[/\\]*}; cd "$d"; cd "../phpunit/phpunit" && pwd)

# See if we are running in Cygwin by checking for cygpath program
if command -v 'cygpath' >/dev/null 2>&1; then
        # Cygwin paths start with /cygdrive/ which will break windows PHP,
        # so we need to translate the dir path to windows format. However
        # we could be using cygwin PHP which does not require this, so we
        # test if the path to PHP starts with /cygdrive/ rather than /usr/bin
        if [[ $(which php) == /cygdrive/* ]]; then
                dir=$(cygpath -m "$dir");
        fi
fi

dir=$(echo $dir | sed 's/ /\ /g')
"${dir}/phpunit" "$@"

It seems to be outputting the script instead of executing it.

I'm running latest Homestead on Windows 10 with PHP 7.1.0-2+deb.sury.org~xenial+1 (cli) ( NTS )

PS. PHPUnit works as expected.

[Doc] Missing dusk option referenced in the doc

Hi!

Doc indicates

The dusk command accepts any argument that is normally accepted by the PHPUnit test runner, allowing you to only run the tests for a given group, etc:

php artisan dusk --group foo

But...

unrecognized option --group foo

The DuskCommand doesn't reference this option.

Assert path doesn't work when Laravel run in a subfolder

Using the following config:
APP_URL=http://local7.dev/Quincalla/public

Page Code:

class HomePage extends Page
{
    public function url()
    {
        return '/';
    }

    public function assert(Browser $browser)
    {
        $browser->assertPathIs($this->url());
    }
}

Error returned:

There was 1 failure:

1) Tests\Browser\CartTest::testAddProductToCart
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'/'
+'/Quincalla/public/'

A temporal solution to sort that was changing the url method on the HomePage to:

public function url()
{
    return parse_url(config('app.url'))['path'] . '/';
}

Other solution could be modifying the method assertPathIs in MakesAssertions class as this:

public function assertPathIs($path)
{
    PHPUnit::assertEquals(parse_url(config('app.url'))['path'] . $path, parse_url(
        $this->driver->getCurrentURL()
    )['path']);

    return $this;
}

Any thoughts?

Compatibility with Valet

I'm running Valet with Laravel 5.4 installed. My dev url is:

http://dusk.dev/

I'm using the default Laravel welcome screen. I then modified the DuskTestCast.php file:

<?php

namespace Tests;

use Laravel\Dusk\TestCase as BaseTestCase;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        return RemoteWebDriver::create(
            'http://dusk.dev:9515', DesiredCapabilities::chrome()
        );
    }
}

I run "php artisan dusk" which I get the following:

Jordans-MacBook-Pro:dusk jordandalton$ php artisan dusk
PHPUnit 5.7.5 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 1.5 seconds, Memory: 10.00MB

There was 1 failure:

1) Tests\Browser\ExampleTest::testBasicExample
Did not see expected text [Laravel] within element [body].
Failed asserting that false is true.

/Users/jordandalton/Code/Projects/dusk/vendor/laravel/dusk/src/Concerns/MakesAssertions.php:140
/Users/jordandalton/Code/Projects/dusk/vendor/laravel/dusk/src/Concerns/MakesAssertions.php:111
/Users/jordandalton/Code/Projects/dusk/tests/Browser/ExampleTest.php:20
/Users/jordandalton/Code/Projects/dusk/vendor/laravel/dusk/src/TestCase.php:84
/Users/jordandalton/Code/Projects/dusk/tests/Browser/ExampleTest.php:21

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

I place a logging point in the MakeAssertions.php file in the Dusk vendor folder

<?php

namespace Laravel\Dusk\Concerns;

use Illuminate\Support\Str;
use Facebook\WebDriver\WebDriverBy;
use PHPUnit_Framework_Assert as PHPUnit;
use Facebook\WebDriver\Exception\NoSuchElementException;

trait MakesAssertions
{
    /// removed..

    /**
     * Assert that the given text appears within the given selector.
     *
     * @param  string  $selector
     * @param  string  $text
     * @return $this
     */
    public function assertSeeIn($selector, $text)
    {
        $fullSelector = $this->resolver->format($selector);

        $element = $this->resolver->findOrFail($selector);
        
        \Log::info($element->getText());
        
        PHPUnit::assertTrue(
            Str::contains($element->getText(), $text),
            "Did not see expected text [{$text}] within element [{$fullSelector}]."
        );

        return $this;
    }

    // removed....
}

I'm my laravel.log file I see the following:

[2017-01-14 00:43:32] local.INFO: 404 - Not Found 

I get the same error regardless of using localhost or dusk.dev with either the chome() and firefox() browser.

unrecognized option --env

  • Laravel Version: 5.5.0
  • PHP Version: 7.1.0
  • Database Driver & Version: N/A

Description:

Setting the environment when running php artisan dusk --env=testing throws unrecognized option --env. However, when running php artisan dusk -h, it includes the following option --env[=ENV] The environment the command should run under. Probably a conflict with PHPUnit?

Steps To Reproduce:

  1. Setup Laravel
  2. Setup Dusk
  3. Create .env.dusk.testing
  4. Run php artisan dusk --env=testing

Workaround

Run APP_ENV=testing php artisan dusk. N.B. For some reason, the Dusk will pick up .env.dusk.testing, but you'll have to set APP_ENV=testing in .env.dusk.testing, else the app will assume it's running in the production environment.

Support for LTS version of Laravel.

Most of the products which are built on Laravel are mostly not on the latest version of Laravel. Will it be a breakable change to push dusk on Laravel 5.1 support? Practically speaking its look very weird to upgrade product in every 6 months. Product team focuses on adding new features rather focusing on upgrading framework. For me, there should be at least one version in every series which has LTS support. This way team can focus on upgrading from one LTS to another.

https://laravel-news.com/laravel-release-process

File permission set wrong after pulling in with composer

The binary files within bin are set to 0664 after I install dusk. I ran chmod -R 0755 vendor/laravel/dusk/bin to fix this, but I have a feeling this will just get overwritten when updating the package. I'm assuming that permissions are not set right somewhere, either on my machine or with the dusk package. Either way, quite a few people seem to be having similar issues. Any thoughts or finger pointing (at me) would be appreciated.

Test methods influence each other through session

Test methods should not influence each other. However, the following two methods share the same session and the second will fail, because the user is already logged in.

    public function test_login_redirects_on_first_time()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/') // has RedirectIfAuthenticated middleware to /dashboard
                ->type('username', 'johndoe')
                ->type('password', 'secret')
                ->press('@login')
                ->assertPathIs('/dashboard');
        });
    }

    public function test_session_from_previous_method_should_not_exist()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                ->assertPathIs('/');  // actually is /dashboard
        });
    }

The issue is fixed if the last line, closeAllButPrimary() is changed to closeAll():

    public function browse(Closure $callback)
    {
        $browsers = $this->createBrowsersFor($callback);

        try {
            $callback(...$browsers->all());
        } catch (Exception $e) {
            $this->captureFailuresFor($browsers);

            throw $e;
        } catch (Throwable $e) {
            $this->captureFailuresFor($browsers);

            throw $e;
        } finally {
-            static::$browsers = $this->closeAllButPrimary($browsers);
+            static::$browsers = $this->closeAll($browsers);
        }
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.