Cypress 10组件测试报错:缺少合适文件加载器求助
问题修复:Cypress组件测试挂载JS组件时的Loader报错
问题场景
使用Cypress 10进行组件测试,仓库以JavaScript为主,初始化Cypress时默认启用TypeScript,基础测试可正常运行,但挂载Loading组件时持续抛出错误:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
问题根源
当前Webpack配置仅针对.ts文件配置了转译规则,未处理包含JSX语法的.js文件,同时缺少对.jsx、.tsx后缀的解析支持,导致无法识别并转译React组件文件。
修复方案
1. 更新Webpack配置(src/config/cypress.webpack.config.js)
扩展文件后缀解析范围,添加对JSX/TSX的支持;同时修改转译规则,覆盖所有React相关文件类型,并确保Babel包含React预设以处理JSX语法:
const webpack = require('webpack'); const { resolve } = require('path'); const config = require('@placehold-cloud-services/frontend-components-config'); const { config: webpackConfig, plugins } = config({ rootFolder: resolve(__dirname, '../'), }); plugins.push( new webpack.DefinePlugin({ insights: { chrome: { isProd: false } } }) ); module.exports = { mode: 'development', devtool: 'eval-source-map', resolve: { // 添加JSX、TSX后缀,支持React组件文件解析 extensions: ['.ts', '.tsx', '.js', '.jsx'], }, module: { rules: [ { // 匹配所有TS/TSX/JS/JSX文件 test: /\.(ts|tsx|js|jsx)$/, exclude: [/node_modules/], use: [ { loader: 'babel-loader', options: { // 添加React预设,转译JSX语法 presets: ['@babel/preset-react', '@babel/typescript'], }, }, ], }, ], }, };
2. 调整Cypress的TypeScript配置(src/cypress/tsconfig.json)
开启对JS文件的编译支持,同时扩展文件包含范围:
{ "compilerOptions": { "target": "es5", "lib": ["es5", "dom"], "types": ["cypress", "node"], // 允许编译JS文件 "allowJs": true, // 识别JSX语法 "jsx": "react" }, // 包含所有测试相关的TS/JS/TSX/JSX文件 "include": ["**/*.ts", "**/*.js", "**/*.tsx", "**/*.jsx"] }
3. 修正组件挂载写法(Loading.cy.ts)
Cypress React挂载需要传入组件实例而非组件对象,同时可省略已配置的文件后缀:
import Loading from './PresentationalComponents/Loading/Loading' import { mount } from 'cypress/react'; describe('Loading.cy.ts', () => { mount(<Loading />) })
验证
修改配置后重新运行Cypress组件测试,Loading组件应能正常挂载,loader报错消失。
内容的提问来源于stack exchange,提问作者Adonis Puente
相关产品推荐
相关产品推荐

