You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Dusk测试click()失效,如何定义指定选择器?

Troubleshooting "Unable to locate element" in Laravel Dusk 5.5

Hey there, let's work through this Dusk element not found issue together. That error means Dusk can't locate your login button using the selector body [dusk="login-button"], so let's break down the most common fixes:

  • Wait for the element to finish loading
    Dusk sometimes tries to interact with elements before the page fully renders. Instead of clicking directly, use Dusk's built-in wait methods to ensure the element is visible first:

    $browser->visit('/login')
            ->waitFor('@login-button') // Waits up to 5 seconds for the element
            ->click('@login-button');
    

    The @ symbol is Dusk's shortcut for targeting elements by their dusk attribute—@login-button directly maps to the selector [dusk="login-button"].

  • Confirm the dusk attribute is correctly rendered
    Open your login page in a regular browser, right-click the login button, and select "Inspect" to check the raw HTML. Make sure the button tag has exactly dusk="login-button" (no typos, extra spaces, or mismatched quotes). For example:

    <button dusk="login-button" type="submit">Login</button>
    

    Also run php artisan view:clear to clear cached Blade templates—sometimes your changes don't show up because of old cached views.

  • Double-check your test's page navigation
    Ensure your test is visiting the correct login route. If you're using $browser->visit('/login'), confirm this route actually loads your resources/views/forms/user/login.blade.php template. A wrong route means Dusk is looking for the button on an entirely different page.

  • Use a more explicit CSS selector
    If the @ shortcut isn't working, try targeting the element with a specific CSS selector:

    $browser->click('button[dusk="login-button"]');
    

    If the button is inside a specific container, narrow it down further for better accuracy:

    $browser->click('#login-form button[dusk="login-button"]');
    
  • Rule out iframes (unlikely for login pages, but worth checking)
    If your login button is inside an iframe (rare for standard login flows), Dusk can't see it until you switch to the iframe first:

    $browser->switchToFrame('iframe-id-or-name')
            ->click('@login-button')
            ->switchToParentFrame();
    

Start with the wait method and verifying the rendered attribute—those are the most common culprits here!

内容的提问来源于stack exchange,提问作者Minerva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:41:54