How to click link icon with laravel dusk?
Asked Answered
T

3

10

If I have a link:

<a href="/somewhere">Click Me</a>

I know I can clickLink based on its text.

public function testCanClickLink()
{
    $this->browse(function ($browser) {
        $browser->visit('/welcome')
                ->clickLink('Click Me');
    });
}

But how can I click an icon link?

<a href="/somewhere">
    <i class="fa fa-plus" aria-hidden="true"></i>
</a>
Tabulator answered 26/2, 2017 at 16:3 Comment(0)
W
9

You can target the href like this:

->click('a[href="/somewhere"]')

Wulfe answered 21/7, 2017 at 14:9 Comment(0)
T
2

This is a bit hacky, but it's what I've come up with as a workaround.

  1. Put an id selector on the link.

    <a id="link-click-me" href="/somewhere">
        <i class="fa fa-plus" aria-hidden="true"></i>
    </a>
    
  2. Assert it's visible.

  3. Get the href attribute.
  4. Visit it.
  5. Assert path is correct.

    public function testCanClickLink()
    {
        $this->browse(function ($browser) {
            $browser->visit('/welcome')
                    ->assertVisible('#link-click-me')
                    ->visit(
                        $browser->attribute('#link-click-me', 'href')
                    )
                    ->assertPathIs('/somewhere');
        });
    }
    
Tabulator answered 26/2, 2017 at 16:46 Comment(1)
This does not preform click action, which subsequently causes redirect. Therefore if there would be running some broken javascript on page, which would prevent redirection by user's click, this approach will not prevent us from headache.Cordwood
L
0

I had the same doubt... and worst, I couldn't use href as a reference to clickable element because I just needed to open a modal. So, my solution was use the dusk attribute, like this:

<a dusk="link-click-me" href="">
    <i class="fa fa-plus" aria-hidden="true"></i>
</a>

And... in my test code, run this line:

$browser->click('@link-click-me');

Enjoy! o/

Laclair answered 15/8, 2023 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.