Node 18+中Jest+jsdom环境下vm.runInContext无法访问window对象
问题:Node 18+中使用vm.runInContext访问window时报"window is not defined"
开发项目时通过vm.runInContext加载测试所需的所有公共文件,该逻辑在Node 16中运行正常,但在Node 18及以上版本(如Node 20)中尝试访问window对象时,抛出"window is not defined"错误。
相关文件信息
package.json
{ "name": "jsdom-tes", "version": "1.0.0", "main": "index.js", "scripts": { "test": "jest" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0" }, "dependencies": { "jsdom": "^24.1.0" } }
Jest配置文件
const config = { testEnvironment: 'jsdom', setupFilesAfterEnv: [ "<rootDir>/jestSetup.js"], testMatch: ["<rootDir>/test/__test__/mytest.test.js"], };
jest初始化文件(jestSetup.js)
const vm = require('node:vm'); const fs = require( "fs" ); const ctx = vm.createContext(global); ctx.hello = "helloworld"; ctx.window = "window"; const sContents = 'var a =1' try { const result = vm.runInContext(`${sContents}; console.log(hello); console.log(window) `, ctx); } catch(e) { console.log(e.stack, 'err1'); console.log('x is', ctx.x) } module.exports = config;
Node 20中运行错误信息
evalmachine.<anonymous>:12 ; console.log(hello); console.log(window) ^ ReferenceError: window is not defined System: OS: macOS 14.5 CPU: (12) arm64 Apple M3 Pro Binaries: Node: 20.14.0 - ~/.nvm/versions/node/v20.14.0/bin/node npm: 10.7.0 - ~/.nvm/versions/node/v20.14.0/bin/npm npmPackages: jest: ^29.7.0 => 29.7.0
复现步骤
运行命令:nvm use 20; npm run test;
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

