在Playwright测试脚本中调用REST接口遇jQuery未定义问题求助
解决Playwright测试中
ReferenceError: $ is not defined的问题 错误原因
你的测试代码运行在Node.js环境(Playwright的测试脚本执行环境),而非浏览器页面中。你安装的@types/jquery仅提供TypeScript类型定义,并没有在Node.js环境中加载jQuery库本身。而且在Playwright测试场景下,完全不需要依赖jQuery发起HTTP请求——Playwright自带了更适配的API。
推荐解决方案:使用Playwright原生request API
Playwright测试函数可以直接获取request对象,用于发起HTTP请求,无需额外依赖第三方库,代码更简洁且贴合测试流程:
import { test, expect } from '@playwright/test'; test('创建会话并获取SESSION_ID', async ({ request }) => { // 发起GET请求创建会话 const response = await request.get('http://xxxxxx.yyyyyy.com:8080/ords/hero_ords/heroapps/v1/mysession'); // 解析返回的JSON响应 const responseData = await response.json(); // 提取SESSION_ID const sessionId = responseData.SESSION_ID; console.log('获取到的SESSION_ID:', sessionId); // 后续将SESSION_ID加入URL的示例(比如访问带会话的页面) await request.get(`http://xxxxxx.yyyyyy.com/target-page?session=${sessionId}`); // 若需通过浏览器页面访问,可使用page对象: // await page.goto(`http://xxxxxx.yyyyyy.com/target-page?session=${sessionId}`); });
不推荐方案:在Node.js中引入jQuery(仅作参考)
如果一定要使用jQuery,需要先安装jQuery本体并配置适配Node.js环境的XMLHttpRequest,但这种方式冗余且没必要:
- 安装jQuery及依赖:
npm install jquery xmlhttprequest
- 修改测试脚本:
import { test, expect } from '@playwright/test'; import $ from 'jquery'; // 为jQuery绑定Node.js环境的XMLHttpRequest实现 $.ajaxSettings.xhr = function() { return new (require('xmlhttprequest').XMLHttpRequest)(); }; test('使用jQuery发起请求', async () => { const settings = { url: "http://xxxxxx.yyyyyy.com:8080/ords/hero_ords/heroapps/v1/mysession", method: "GET", timeout: 0, }; $.ajax(settings).done(function (response) { console.log(response); const sessionId = response.SESSION_ID; // 后续操作逻辑 }); });
内容的提问来源于stack exchange,提问作者JoseAróstegui
相关产品推荐
相关产品推荐

