Laravel Dusk测试click()失效,如何定义指定选择器?
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 theirduskattribute—@login-buttondirectly 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 exactlydusk="login-button"(no typos, extra spaces, or mismatched quotes). For example:<button dusk="login-button" type="submit">Login</button>Also run
php artisan view:clearto 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 yourresources/views/forms/user/login.blade.phptemplate. 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

