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

VanillaJS项目执行Jest测试时出现JSDOM TypeError问题求助

问题分析

该错误是由于jsdom v22+版本与Jest 29.x自带的jest-environment-jsdom环境冲突导致的,手动导入jsdom会破坏Jest预设的DOM环境原型链,从而抛出TypeError: Cannot convert undefined or null to object错误。近期依赖更新(如自动拉取了jsdom新版本)是触发问题的直接原因。

解决方案

方案1:移除手动导入的jsdom,改用Jest原生jsdom环境

这是最推荐的解决方式,因为Jest的jest-environment-jsdom已经内置了完整的DOM环境,无需手动引入jsdom:

  1. 修改测试文件,删除import jsdom, {JSDOM} from "jsdom",调整DOM加载逻辑:
    import {fireEvent, getByTestId} from "@testing-library/dom"
    import "@testing-library/jest-dom/extend-expect"
    import path from "path"
    import fs from "fs"
    
    const BASE = path.resolve(__dirname, "../src");
    const htmlContent = fs.readFileSync(`${BASE}/index.html`, 'utf8');
    
    let body
    
    describe("stack operation test", function () {
      beforeEach(async () => {
        // 直接将HTML注入Jest提供的document对象
        document.body.innerHTML = htmlContent;
        body = document.body
        // 模拟alert方法
        jest.spyOn(window, 'alert').mockImplementation(() => {});
      })
    
      it("Clicking on the push button should push the item to the bottom of the stack board", async function () {
        const input = getByTestId(body, "input")
        await typeText(input, "item1")
        // 后续测试逻辑...
      })
    })
    
  2. 在jest.config.js中明确指定测试环境为jsdom:
    module.exports = {
        clearMocks: true,
        setupFilesAfterEnv: ['regenerator-runtime/runtime'],
        testEnvironment: 'jsdom', // 新增该行
        transformIgnorePatterns: [
            "/node_modules/",
        ],
        testPathIgnorePatterns: [
            "/node_modules/",
        ],
        useStderr: true
    };
    

方案2:降级jsdom到兼容版本

如果必须手动使用JSDOM实例,将jsdom降级到v21.x版本(该版本与Jest 29.x兼容性更好):

npm uninstall jsdom
npm install jsdom@21.1.2 --save-dev

方案3:修正Jest转译配置

当前transformIgnorePatterns中对jsdom的例外配置可能导致错误转译,修改为:

module.exports = {
    clearMocks: true,
    setupFilesAfterEnv: ['regenerator-runtime/runtime'],
    transformIgnorePatterns: [
        "/node_modules/", // 移除jsdom的例外,jsdom无需被Babel转译
    ],
    testEnvironment: 'jsdom',
    testPathIgnorePatterns: [
        "/node_modules/",
    ],
    useStderr: true
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:53:15