Cypress中使用OTPAuth时Webpack编译出现Unexpected Token错误
解决Cypress中OTPAuth库的Webpack编译错误
问题描述
在Cypress自动化测试中实现注册流程的OTP生成功能,编写代码如下:
import OTPAuth from 'otpauth'; const qrcode = new Decoder(); cy.get('img[alt="QR Code"]').then(image => { const src = image.prop('src'); const decoded = qrcode.scan(src); const totp = OTPAuth.URI.parse(decoded.data); const generateOTP = totp.generate(); cy.get('input#code').type(generateOTP); })
运行时触发Webpack编译错误:
Error: Webpack Compilation Error ./node_modules/otpauth/dist/otpauth.esm.js 970:28 Module parse failed: Unexpected token (970:28) Module parse failed: Unexpected token (970:28) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. | const randomBytes = size => { | { > if (!globalScope.crypto?.getRandomValues) { | throw new Error("Cryptography API not available"); | } @ ./cypress/e2e/tests/invitation-portal-invitation.cy.js 18:38-56 ...(省略后续错误栈)
错误原因
Cypress 12.13.0内置的Webpack版本不支持ES2020的可选链操作符(?.),而otpauth v9及以上版本的代码中使用了该语法,导致Webpack无法解析。
解决方案
方案1:降级otpauth版本
安装v8.x版本的otpauth,该版本未使用新语法,可直接兼容Cypress内置Webpack:
npm install otpauth@8.x --save-dev
方案2:配置Babel转译otpauth库
修改Cypress的Webpack配置,让Babel处理node_modules中的otpauth代码:
- 安装必要依赖:
npm install @babel/core @babel/preset-env babel-loader --save-dev
- 在项目根目录创建
cypress/webpack.config.js,添加配置:
module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules\/(?!otpauth)/, // 仅对otpauth进行转译 use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } };
- 在
cypress.config.js中指定Webpack配置:
const { defineConfig } = require("cypress"); const webpackConfig = require('./cypress/webpack.config.js'); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { const webpackPreprocessor = require('@cypress/webpack-preprocessor'); on('file:preprocessor', webpackPreprocessor({ webpackOptions: webpackConfig })); }, }, });
方案3:使用Cypress专用OTP插件
改用cypress-otp插件,它封装了OTP生成逻辑,无需手动处理依赖编译:
- 安装插件:
npm install cypress-otp --save-dev
- 在
cypress/support/e2e.js中导入:
import 'cypress-otp';
- 修改测试代码:
cy.get('img[alt="QR Code"]').then(image => { const src = image.prop('src'); cy.decodeQrCode(src).then(otpAuthUri => { cy.generateOTP(otpAuthUri).then(otp => { cy.get('input#code').type(otp); }); }); });
内容的提问来源于stack exchange,提问作者Pedro
相关产品推荐
相关产品推荐

