Open Jinx-1120 opened 8 months ago
在业务场景中只需要对组件进行单元测试,对于业务侧的场景基本不会写测试case。对于taro相关的api完全可以通过mock去做,因此vitest理论上也是可以运行的?
在jest中可以通过moduleNameMapper: {
'@tarojs/taro$': resolve(__dirname, './runtime/taro-h5.js'),
'@tarojs/components$': '@tarojs/components/lib/react/index'
},
对@tarojs/taro和@tarojs/components做映射
同样的切换到vitest之后使用resolve.alias进行类似的映射处理
resolve: {
alias: {
'@tarojs/components': '@tarojs/components/lib/react/index.js',
'@tarojs/taro': '@tarojs/taro-h5',
},
},
但是运行vitest会出现:
Error: Failed to resolve import "@tarojs/components/dist/components" from "node_modules/.pnpm/@tarojs+components@3.6.20_@types+react@17.0.78_postcss@8.4.36_react@18.2.0/node_modules/@tarojs/components/lib/react/components.js". Does the file exist?
@ZakaryCode 大佬有什么建议或者解决方案吗?
``我成功迁移到vitest了,只需要注意两点:
export default defineConfig({ //需要在最外层的resolve添加映射,否则需要自行在setup文件内一一进行mock resolve: { alias: { '@tarojs/components': '@tarojs/components/dist-h5/react', '@tarojs/taro': '@tarojs/taro-h5', '@': path.resolve(__dirname, 'src'), }, }, test: { globals: true, environment: 'jsdom', // 这个文件内执行初始化 setupFiles: './vitest.setup.js', include: ['src/**/*.test.{js,jsx,ts,tsx}'], // 不建议解析css文件 css: false, }, // 最关键的是esbuild跳过taro编译 esbuild: { loader: 'tsx', include: [/src\/.*\.[jt]sx?$/], exclude: /node_modules\/(?!@taro)/, }, })
然后在vitest.setup.js文件内导入testing-library
import '@testing-library/jest-dom/vitest';
就可以愉快的使用testing-library和vitest进行集成测试了!
import Alert from '.'; import { describe, expect, test } from 'vitest'; import { render, fireEvent } from '@testing-library/react'; describe('Alert', () => { test('测试渲染', async () => { const msg = '123321'; const { container } = render(<Alert message={msg} />); expect(container.querySelector(
.finance-alert__msg)?.innerHTML).toMatch(msg); }); });
相关平台
微信小程序
复现仓库
https://github.com/Jinx-1120/test-taro-vitest.git 小程序基础库: 3.0.0 使用框架: React
复现步骤
pnpm i
pnpm run test
期望结果
希望vitest能够正常运行
实际结果
Error: Failed to resolve import "@tarojs/components/dist/components" from "node_modules/@tarojs/components/lib/react/components.js". Does the file exist?
环境信息