Jest运行KnockoutJS单元测试报ReferenceError: ko is not defined错误
问题根因
运行测试抛出ReferenceError: ko is not defined是因为Jest运行在Node环境,不会像浏览器环境那样自动把脚本标签引入的Knockout注入为全局变量;同时你的业务代码/测试入口没有显式导入knockout模块,运行时找不到ko对象。
解决方法
选其中一种方案即可:
- 方案1(符合ES Module规范,优先推荐):在所有使用了Knockout API的业务文件(比如
loginPage.js、Home.js)顶部,显式导入knockout:
import ko from 'knockout';
如果是CommonJS规范的旧文件,替换为:
const ko = require('knockout');
- 方案2(适合存量老项目,无需逐个修改业务文件):通过Jest配置提前把ko挂载到全局
- 项目根目录新建
jest.setup.js文件,写入以下内容:
import ko from 'knockout'; global.ko = ko; // 如果业务代码直接使用全局$、jQuery,可一并挂载 import $ from 'jquery'; global.$ = $; global.jQuery = $;- 修改
package.json中的jest配置段,添加setupFiles字段指向刚才创建的配置文件:
"jest": { "setupFiles": ["./jest.setup.js"], "reporters": [ "default", [ "jest-html-reporters", { "publicPath": "./html-report", "filename": "report.html", "openReport": false } ] ], "collectCoverage": true } - 项目根目录新建
额外配置校验
你当前项目开启了ES Module模式("type": "module"),需要保证Babel配置正常,否则Jest可能无法正确解析ES模块语法。在项目根目录新建babel.config.json,写入以下配置:
{ "presets": [ ["@babel/preset-env", { "targets": { "node": "current" } }] ] }
配置修改完成后,首次运行测试建议加--no-cache参数跳过Jest缓存,避免旧配置干扰:
npm test -- --no-cache
内容的提问来源于stack exchange,提问作者anxiousAJ
相关产品推荐
相关产品推荐

