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

在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,但这种方式冗余且没必要:

  1. 安装jQuery及依赖:
npm install jquery xmlhttprequest
  1. 修改测试脚本:
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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:55:16