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

如何用Jest测试基于jQuery的异步JSON数据获取函数?

问题分析与解决方案

1. 首先修复 registration.js 中的语法错误

你遇到的 SyntaxError 是因为在 registration.js 中使用了顶层 await,这在 CommonJS 模块(使用 module.exports 的模块)中是不允许的。只需移除或注释掉那行顶层 await 代码即可:

async function readJSONFile(url) {
    const data = await $.getJSON(url);
    return data;
}

// 移除或注释掉这行,因为顶层 await 在 CommonJS 中无效
// let returnedData = await readJSONFile(testURL);

module.exports = readJSONFile;

2. 编写正确的 Jest 测试文件

核心问题修正:

  • 正确导入 readJSONFile 函数(原代码中多了 .readJSONFile,因为模块直接导出了函数)
  • 模拟 jQuery 的 $.getJSON 方法,避免发起真实网络请求
  • 测试目标函数 readJSONFile,而非直接调用 $.getJSON
  • 使用 toEqual 而非 toBe 比较对象值(toBe 检查引用相等,toEqual 检查值相等)

最终测试代码:

const readJSONFile = require("../JS/registration.js");

// 全局模拟 jQuery 的 getJSON 方法
global.$ = {
    getJSON: jest.fn()
};

test("check if the data is retrieved", async () => {
    // 定义测试用的数据和 URL
    const testData = {
        "courseName": {
            "instrName": "profName",
            "location": "classLocation",
            "timings": "classTimings"
        }
    };
    const testURL = "mock-test-url.json";

    // 让模拟的 getJSON 返回测试数据
    global.$.getJSON.mockResolvedValue(testData);

    // 调用待测试的函数
    const result = await readJSONFile(testURL);

    // 验证 getJSON 被正确调用
    expect(global.$.getJSON).toHaveBeenCalledWith(testURL);
    // 验证返回数据与预期一致
    expect(result).toEqual(testData);
});

额外说明

如果你希望在 registration.js 中保留顶层 await,可以将模块切换为 ES 模块:

  1. 在 package.json 中添加 "type": "module"
  2. 将 module.exports = readJSONFile 改为 export default readJSONFile
  3. 测试文件中使用 import readJSONFile from "../JS/registration.js" 导入函数

内容的提问来源于stack exchange,提问作者prav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:12:31