如何用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 模块:
- 在
package.json中添加"type": "module" - 将
module.exports = readJSONFile改为export default readJSONFile - 测试文件中使用
import readJSONFile from "../JS/registration.js"导入函数
内容的提问来源于stack exchange,提问作者prav
相关产品推荐
相关产品推荐

