Search code examples
wordpresslaravelunit-testingauthenticationlaravel-dusk

laravel dusk test login to wordpress unable to set cookie


I am using laravel dusk to login to a wordpress site using the function below

 public function testLoginPage()
{
    $this->browse(function (Browser $browser) {
        $browser->visit('http://localhost/wordpress/wp-login.php')
            ->waitFor('#wp-submit')
            ->value('#user_login', '***')
            ->value('#user_pass', '***')
            ->click('#wp-submit')
            ->waitFor('#footer-thankyou')
            ->assertSee('Thank you for creating with');
        $this->saveCookies($browser);
    });
}

and saving the cookie created

protected $cookie_file = 'cookies.txt';

private function saveCookies(Browser $browser) {
    $cookies = $browser->driver->manage()->getCookies();
    file_put_contents($this->cookie_file, serialize($cookies));
}
private function loadCookies(Browser $browser) {
    if (file_exists($this->cookie_file)) {
        //Get cookies from storage
        $cookies = unserialize(file_get_contents($this->cookie_file));
        //Add each cookie to this session
        foreach ($cookies as $key => $cookie) {
            $browser->driver->manage()->addCookie($cookie);
        }
    }
}

Now I login successfully and the cookie also gets createdenter image description here

But when I try A page in the admin like the update page I get the error that unable to set cookie (Session info: chrome=86.0.4240.75)

public function testUpdateAllPlugins()
{
    $this->browse(function (Browser $browser) {
        $this->loadCookies($browser);
        $browser->visit('http://localhost/wp-admin/update-core.php')
            ->waitFor('#plugins-select-all')
            ->check('#plugins-select-all')
            ->click('#upgrade-plugins')
            #->withinFrame('iframe[title="Update progress"]', function($browser){
            ->withinFrame('.wrap > iframe', function($browser){
                $browser
                    ->assertSee('All updates have been completed');
            });
    });
}

I need to be able to visit all the admin pages after the login so My question is How Do I set and use the cookie from the laravel dusk to wordpress site. I am using the below namespace in the testcase

namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Facebook\WebDriver\Cookie;
use Facebook\WebDriver\WebDriverOptions;
use Laravel\Dusk\Chrome\ChromeProcess;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;

enter image description here


Solution

  • I got it working using the code for the visit right after the login one instead of setting a cookie and using a different method to visit the browser.