Cypress中TypeError: cy.findByRole is not a function错误的解决方法
修复
cy.findByRole is not a function错误的方案 1. 确认Cypress全局命令入口配置
Cypress 10+版本中,cypress/support/e2e.ts(旧版为index.ts)是全局命令的加载入口,必须确保该文件导入了commands.ts:
// cypress/support/e2e.ts import './commands'
2. 完善Cucumber预处理器配置
使用@badeball/cypress-cucumber-preprocessor时,需在cypress.config.ts中正确配置预处理器,保证全局命令能被Cucumber步骤文件识别。示例配置:
import { defineConfig } from 'cypress' import createBundler from '@bahmutov/cypress-esbuild-preprocessor' import { addCucumberPreprocessorPlugin } from '@badeball/cypress-cucumber-preprocessor' import createEsbuildPlugin from '@badeball/cypress-cucumber-preprocessor/esbuild' export default defineConfig({ e2e: { specPattern: '**/*.feature', async setupNodeEvents(on, config) { const bundler = createBundler({ plugins: [createEsbuildPlugin(config)], }) on('file:preprocessor', bundler) await addCucumberPreprocessorPlugin(on, config) return config }, }, })
若配置中缺少addCucumberPreprocessorPlugin调用,会导致全局命令无法在步骤文件中生效。
3. 重置依赖与缓存
- 删除现有依赖文件并重新安装:
rm -rf node_modules package-lock.json npm install - 清除Cypress缓存:
npx cypress cache clear
4. 验证TypeScript配置
调整tsconfig.json的include规则,确保覆盖所有测试文件:
{ "compilerOptions": { "target": "es5", "lib": ["es5", "dom"], "types": ["cypress", "@testing-library/cypress"] }, "include": ["cypress/**/*.ts", "**/*.ts"] }
5. 检查命令导入语句
确认cypress/support/commands.ts中的导入无拼写错误:
import '@testing-library/cypress/add-commands'
内容的提问来源于stack exchange,提问作者stein korsveien
相关产品推荐
相关产品推荐

