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

使用Jest测试Owl Carousel时出现Cannot read property 'fn' of undefined异常

Jest测试Owl Carousel时出现"Cannot read property 'fn' of undefined"的原因

问题背景

项目中使用owl.carousel包时业务代码运行正常,但用Jest执行测试用例时,在引入业务文件./codeFile的阶段触发异常,错误提示为**"Cannot read property 'fn' of undefined"**。已知Owl Carousel是挂载在jQuery原型上的函数,问题根源是代码中$.fn.owlCarousel里的$未定义,但不清楚具体原因。

测试用例代码

fit("save button functionality", async ()=>{
    let { addDevice } = require('./codeFile')
    // $.fn.owlCarousel = jest.fn().mockImplementation(()=>{
    //     console.log('using my owl carousel');
    // })
    let addDeviceButton = document.getElementsByClassName("button-link")[0];

    await addDevice(addAnotherDeviceButton);
})

项目package.json配置

{
    "@testing-library/dom": "^6.11.0",
    "@testing-library/jest-dom": "^5.16.5",
    "jest": "^25.0.0",
    "owl.carousel": "^2.3.4",
    "jest-environment-jsdom": "^25.0.0",
    "jest": {
       "testEnvironment": "jsdom",
       "coverageThreshold": {
          "global": {
             "branches": 50,
             "functions": 50,
             "lines": 50,
             "statements": 50
        }
    },
    "transform": {
      "^.+\\.js$": "babel-jest",
      ".+\\.(css|scss|png|jpg|svg)$": "jest-transform-stub"
    }
  }
}

原因分析

  1. Jest环境未全局注入jQuery
    业务运行环境中,jQuery通常是通过<script>标签全局引入的,$会成为全局变量。但Jest的jsdom测试环境默认不会自动引入jQuery,当业务代码(或Owl Carousel源码)尝试访问$.fn时,$本身是undefined,直接抛出错误。

  2. 测试文件中代码执行顺序错误
    你原本打算mock$.fn.owlCarousel,但代码是先引入业务文件,再尝试mock。而业务文件被引入的瞬间就会执行其中的Owl Carousel初始化逻辑,此时$还未被定义或mock,直接触发报错。

  3. package.json配置存在语法错误
    你的package.json里重复定义了"jest"字段:一个是用于指定版本的顶级字段,另一个是用于配置的顶级字段。这种写法会导致Jest无法正确读取配置(比如testEnvironment等设置可能不生效),进一步加剧环境变量缺失的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:46:04