【问题标题】:How can I test swiper with Jest?如何使用 Jest 测试 swiper?
【发布时间】:2021-09-20 05:20:02
【问题描述】:

我正在使用 Jest 创建 Swiper 的单元测试。

这是我的代码:

https://codesandbox.io/s/swiper-default-react-forked-v0dnz?file=/src/App.test.jsx

● Test suite failed to run

    Cannot find module 'swiper/react' from 'src/App.jsx'

    Require stack:
      src/App.jsx
      src/App.test.jsx

      1 | import React from "react";
      2 | // Import Swiper React components
    > 3 | import { Swiper, SwiperSlide } from "swiper/react";
        | ^
      4 |
      5 | // Import Swiper styles
      6 | import "swiper/css";

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:322:11)
      at Object.<anonymous> (src/App.jsx:3:1)

一直报这个错误,但是程序可以正常运行。谁能帮我解决这个问题?

【问题讨论】:

  • 通常你可以假设第三方库已经过作者测试,所以你不需要手动进行
  • @Mhmdrz_A 是的,谢谢,但我的真实页面不仅包含 swiper,还有一些其他的 logi 需要测试。

标签: jestjs swiper.js


【解决方案1】:

我想您在使用 Swiper 7 时遇到了问题,因为 Jest 还不支持 ESM 包。

所以即使不是最优解,也可以通过降级到Swiper 6

来解决

运行这些命令:

npm uninstall swiper
npm install swiper@6.8.4

并以这种方式导入:

import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/swiper-bundle.min.css'
import 'swiper/swiper.min.css'

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2015-10-12
    • 2021-02-14
    • 2021-10-23
    相关资源
    最近更新 更多