使用Puppeteer的waitFor函数遇类型错误,相关写法均无法生效求助
Hey there! Let's break down what's going wrong here and get your wait logic working correctly.
First, the error you're seeing—Unsupported target type: boolean—happens because Puppeteer's waitFor method doesn't accept a raw boolean value as an argument. When you write await page.waitFor(url === 'localhost:3000/blogs'), that expression gets evaluated immediately to true or false before being passed to waitFor, which isn't a valid input type for the method.
Your second attempt, await page.waitFor(url).toEqual('localhost:3000/blogs'), also doesn't work because waitFor(url) returns a Promise, not a string you can call toEqual on directly. Plus, passing a URL string to waitFor isn't the right way to wait for the current page's URL to match a value.
The Correct Approach: Use waitForFunction
To wait until the page's URL matches your target, you need to use waitForFunction, which lets you run a function in the browser context and waits until it returns true. Here are a few solid implementations:
1. Exact URL Match (include protocol!)
Remember that window.location.href returns the full URL, including the protocol (http:// or https://). If you want an exact match, make sure to include that:
await page.waitForFunction(() => { return window.location.href === 'http://localhost:3000/blogs'; });
2. Match Just the Path
If you don't care about the protocol or domain (maybe you're testing across environments), you can check the pathname instead:
await page.waitForFunction(() => { return window.location.pathname === '/blogs'; });
3. Partial Match
If you just need to confirm the URL contains a specific string (like /blogs), use includes:
await page.waitForFunction(() => { return window.location.href.includes('localhost:3000/blogs'); });
Why Your Previous Attempts Failed
Let's recap to avoid these mistakes in the future:
await page.waitFor(url === 'localhost:3000/blogs'): This evaluates toawait page.waitFor(true)orawait page.waitFor(false)—a boolean, whichwaitFordoesn't support.await page.waitFor(url).toEqual(...):waitForreturns a Promise, so you can't chaintoEqualonto it. Also, passing a URL towaitForis meant for waiting for a navigation to that URL (not checking the current URL), which would require combining it withwaitForNavigationinstead.
That should get your wait logic working smoothly!
内容的提问来源于stack exchange,提问作者Taylor Austin

