如何使用 Jest 测试 swiper?

Nei*_*Liu 11 jestjs swiper.js

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

\n

这是我的代码:

\n

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

\n
\xe2\x97\x8f Test suite failed to run\n\n    Cannot find module \'swiper/react\' from \'src/App.jsx\'\n\n    Require stack:\n      src/App.jsx\n      src/App.test.jsx\n\n      1 | import React from "react";\n      2 | // Import Swiper React components\n    > 3 | import { Swiper, SwiperSlide } from "swiper/react";\n        | ^\n      4 |\n      5 | // Import Swiper styles\n      6 | import "swiper/css";\n\n      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:322:11)\n      at Object.<anonymous> (src/App.jsx:3:1)\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

Lai*_*acy 11

我想您在使用Swiper 7或更新版本时遇到问题,因为 Jest 尚不支持 ESM 软件包。

解决方案 1: 对于Swiper 7-9或更高版本:

首先添加到swiper/cssjestmoduleNameMapperpackage.json

  "jest": {
    "moduleNameMapper": {
      "swiper/css": "swiper/swiper.min.css"
    }
  }
Run Code Online (Sandbox Code Playgroud)

其次,您可以模拟 Swiper 组件来渲染其子组件:

jest.mock('swiper/react', () => ({
  Swiper: ({ children }) => <div data-testid="swiper-testid">{children}</div>,
  SwiperSlide: ({ children }) => (
    <div data-testid="swiper-slide-testid">{children}</div>
  ),
}))
Run Code Online (Sandbox Code Playgroud)

如果您还导入了任何其他模块,例如:

  • 对于Swiper 7-9
   // For Swiper 7-9
   import { Navigation, Pagination, Scrollbar, A11y } from 'swiper';
Run Code Online (Sandbox Code Playgroud)
  • 对于Swiper 10-11或更高版本:
   // For Swiper 10-11 or newer versions
   import { Navigation, Pagination, Scrollbar, A11y } from 'swiper/modules';
Run Code Online (Sandbox Code Playgroud)

您可以像这样模拟模块:

  • 对于Swiper 7-9
  jest.mock('swiper', () => ({
    Navigation: (props) => null,
    Pagination: (props) => null,
    Scrollbar: (props) => null,
    A11y: (props) => null,
  }))
Run Code Online (Sandbox Code Playgroud)
  • 对于Swiper 10-11或更高版本:
  jest.mock('swiper/modules', () => ({
    Navigation: (props) => null,
    Pagination: (props) => null,
    Scrollbar: (props) => null,
    A11y: (props) => null,
  }))
Run Code Online (Sandbox Code Playgroud)

最后,作为一个示例,现在您可以编写一个测试来检查有多少张幻灯片呈现为“swiper-slide-testid”的子级:

test('Renders component with 12 slides', () => {
  render(<Component/>)

  const slides = screen.getAllByTestId('swiper-slide-testid')
  expect(slides.length).toBe(12)
  
})
Run Code Online (Sandbox Code Playgroud)

解决方案2:

即使不是最优方案,也可以通过降级到Swiper 6来解决

运行这些命令:

npm uninstall swiper
npm install swiper@6.8.4
Run Code Online (Sandbox Code Playgroud)

并以这种方式导入它:

npm uninstall swiper
npm install swiper@6.8.4
Run Code Online (Sandbox Code Playgroud)