Cypress调用Azure Key Vault工具方法报错:无法遍历依赖图
问题描述
基于TypeScript构建的Cypress自动化框架,包含一个从Azure Key Vault获取密钥的工具方法:
- 通过命令行执行
npm run data.refresh.qa调用initiator.ts中的方法,能成功获取密钥并启动测试 - 直接在测试文件中调用该方法时,触发以下错误:
Error: Can't walk dependency graph: ENOENT: no such file or directory, lstat 'C:\dev\Automation\automated-testing-service\cypress\configurations\fs' required by C:\dev\Automation\automated-testing-service\node_modules@azure\identity\dist\index.js
已确认代码未显式引用该不存在的路径,且该路径下的配置文件与密钥获取逻辑无关。
可能原因
环境差异导致模块解析错误
npm脚本运行在纯Node.js环境,而Cypress测试文件默认在浏览器沙箱环境执行。@azure/identity依赖Node.js核心模块(如fs),浏览器环境中没有这些模块,Cypress解析时错误地将核心模块fs映射到了项目目录下的同名路径,导致找不到文件。Cypress模块解析配置异常
项目中tsconfig.json或cypress.config.ts的模块解析规则可能存在问题,没有正确识别Node.js核心模块,反而将其当作项目内文件去查找。@azure/identity版本兼容性问题
部分版本的@azure/identity在浏览器环境下的适配不完善,未正确处理Node核心模块的替代逻辑。
解决方案
方案1:将密钥获取逻辑移至Cypress插件(Node环境)
Cypress插件文件运行在Node.js环境,适合处理依赖核心模块的逻辑:
- 在
cypress.config.ts中添加自定义任务:
import { defineConfig } from 'cypress'; import { getKeyFromAzureKeyVault } from './path-to-your-initiator'; export default defineConfig({ e2e: { setupNodeEvents(on, config) { on('task', { async getAzureSecret(secretName: string) { return await getKeyFromAzureKeyVault(secretName); }, }); }, }, });
- 在测试文件中通过
cy.task调用:
cy.task('getAzureSecret', 'your-target-secret').then((secret) => { // 在这里使用密钥执行测试操作 });
方案2:调整Cypress配置以支持Node核心模块
修改cypress/tsconfig.json,添加Node类型并修正模块解析:
{ "compilerOptions": { "types": ["cypress", "node"], "moduleResolution": "node", "resolveJsonModule": true } }
如果使用Webpack预处理器,在cypress.config.ts中补充配置,让Node核心模块被正确处理:
import { defineConfig } from 'cypress'; import webpack from '@cypress/webpack-preprocessor'; export default defineConfig({ e2e: { setupNodeEvents(on, config) { const webpackOptions = { resolve: { extensions: ['.ts', '.js'], fallback: { fs: false, // 不需要在浏览器环境模拟fs时设为false path: require.resolve('path-browserify') } }, module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, use: 'ts-loader' } ] } }; on('file:preprocessor', webpack({ webpackOptions })); }, }, });
方案3:调整@azure/identity版本
尝试切换到兼容Cypress双环境的版本,例如:
npm install @azure/identity@3.2.0
(具体版本可根据实际测试调整,优先选择稳定且适配浏览器/Node环境的版本)
验证步骤
- 按上述方案修改后,运行测试文件检查报错是否消失
- 通过
cypress info查看Cypress使用的Node版本,确保与npm run data.refresh.qa执行时的Node版本一致
内容的提问来源于stack exchange,提问作者Zuno

