为什么会出现TypeError: jsdom.createVirtualConsole()不是函数?
问题:运行
learn test时出现jsdom相关TypeError错误 环境背景
- 基于WSL + Ubuntu搭建的开发环境,包含Node.js、Python、Ruby
- 当前jsdom版本:
20.0.3(通过npm list jsdom确认)
错误详情
执行learn test后终端报错:
java-script-intro-to-functions-lab@0.1.0 test mocha --timeout 5000 -R mocha-multi --reporter-options spec=-,json=.results.json 0 passing (106ms) 1 failing 1) "before all" hook in "{root}": TypeError: jsdom.createVirtualConsole is not a function at Context.<anonymous> (test/root.js:18:27) at process.processImmediate (node:internal/timers:471:21)
尝试将virtualConsole改为new jsdom.VirtualConsole().sendTo(console)后,出现新错误:
TypeError: jsdom.env is not a function
相关代码文件
test/root.js
global.expect = require("expect"); const babel = require("babel-core"); const jsdom = require("jsdom"); const path = require("path"); before(function (done) { const babelResult = babel.transformFileSync( path.resolve(__dirname, "..", "index.js"), { presets: ["es2015"], } ); const html = path.resolve(__dirname, "..", "index.html"); jsdom.env( html, [], { src: babelResult.code, virtualConsole: jsdom.createVirtualConsole().sendTo(console), }, (err, window) => { if (err) { return done(err); } Object.keys(window).forEach((key) => { global[key] = window[key]; }); return done(); } ); });
package.json(npm audit --fix --force更新后)
"devDependencies": { "babel-core": "^6.11.4", "babel-preset-es2015": "^6.9.0", "expect": "^1.20.2", "jsdom": "^20.0.3", "mocha": "^10.2.0", "mocha-jsdom": "~1.1.0", "mocha-multi": "^1.1.3" }
package.json(npm audit --fix --force前原始版本)
"devDependencies": { "babel-core": "^6.11.4", "babel-preset-es2015": "^6.9.0", "expect": "^1.20.2", "jsdom": "^9.2.1", "mocha": "5.2.0", "mocha-jsdom": "~1.1.0", "mocha-multi": "^1.1.3" }
操作过程
运行npm audit --fix --force后,终端输出:
npm WARN using --force Recommended protections disabled. npm WARN
audit Updating jsdom to 20.0.3, which is a SemVer major change. npm
WARN audit Updating mocha to 10.2.0, which is a SemVer major change.
该命令强制更新了jsdom和mocha的大版本,导致与原有测试代码API不兼容。
解决办法
通过从GitHub重新安装实验环境,并忽略依赖问题警告,当前测试已能正常运行。
内容的提问来源于stack exchange,提问作者Giselle Smith
相关产品推荐
相关产品推荐

