Playwright TypeScript脚本报错:Type 'void'不可分配给'Response | undefined'
解决Playwright TypeScript中
route.continue()赋值导致的类型错误 问题根源
route.continue()方法的返回值是void,它仅用于让拦截的请求继续发送,不会返回请求的响应对象。你试图将它赋值给类型为Response | undefined的loginResponse变量,因此触发了TypeScript的类型不匹配错误。
正确修改方案
根据需求场景,有两种常用解决方式:
方案1:使用route.fetch()直接获取响应
如果需要在路由回调内部获取响应,可替换route.continue()为route.fetch(),该方法返回Promise<Response>,完全匹配loginResponse的类型:
let loginResponse: Response | undefined; await page.route('/api/login', async (route) => { // 发送请求并获取响应 loginResponse = await route.fetch(); // 若需原请求继续到达目标服务器,需额外调用route.continue() await route.continue(); }); // 后续使用响应对象做断言等操作 if (loginResponse) { expect(await loginResponse.json()).toEqual({ success: true }); }
方案2:结合page.waitForResponse()监听响应
如果无需在路由回调内处理响应,可在外部等待特定请求的响应,配合路由拦截使用:
// 启动路由拦截,让请求正常流转 await page.route('/api/login', async (route) => { await route.continue(); }); // 触发登录操作的同时,等待目标响应 const [loginResponse] = await Promise.all([ page.waitForResponse(resp => resp.url().includes('/api/login')), page.click('#login-btn') // 替换为实际触发登录的操作 ]); // 验证响应状态 expect(loginResponse.ok()).toBeTruthy();
注意事项
- 使用
route.fetch()时,它会单独发送一次请求,若需原请求继续到达服务器,必须额外调用route.continue()。 page.waitForResponse()支持通过URL、请求方法等条件过滤响应,能更精准地获取目标请求的结果。
内容的提问来源于stack exchange,提问作者yonatan hornstein
相关产品推荐
相关产品推荐

