Cypress中e2e.js无法导入googleapis的问题求助
问题分析
直接在Cypress浏览器上下文(如support/e2e.js的Before Hook)中引入googleapis包会报错,原因是googleapis依赖Node.js内置的http2模块,而Cypress运行测试的浏览器环境不支持该模块,导致http2.constants未定义。
解决方案
方法一:使用Cypress Task(推荐)
Cypress Task运行在Node.js环境,可直接调用Node模块,完美适配googleapis的运行需求。
- 配置Cypress Task(cypress.config.js)
const { defineConfig } = require('cypress') const { google } = require('googleapis') const fs = require('fs') const path = require('path') module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { on('task', { async uploadToGoogleDrive({ videoPath, credentials, folderId }) { // Google Drive认证 const auth = new google.auth.GoogleAuth({ credentials: credentials, scopes: ['https://www.googleapis.com/auth/drive.file'] }) const drive = google.drive({ version: 'v3', auth }) // 上传视频文件 const fileMetadata = { name: path.basename(videoPath), parents: [folderId] // 指定Drive目标文件夹ID } const media = { mimeType: 'video/mp4', body: fs.createReadStream(videoPath) } const uploadResult = await drive.files.create({ resource: fileMetadata, media: media, fields: 'webViewLink' // 仅返回网页访问链接 }) return uploadResult.data.webViewLink } }) }, }, })
- 在测试完成后调用Task(support/e2e.js)
Cypress.on('after:run', async (results) => { // 遍历所有生成的测试视频 if (results.videos?.length) { for (const video of results.videos) { const webViewLink = await cy.task('uploadToGoogleDrive', { videoPath: video.path, credentials: require('../../google-credentials.json'), // 你的服务账号密钥文件 folderId: '替换为你的Drive文件夹ID' }) // 可将链接写入日志、测试报告或其他存储 console.log(`视频已上传:${webViewLink}`) } } })
方法二:独立Node脚本(测试后批量上传)
如果不想修改Cypress配置,可在测试完成后用独立脚本批量上传视频。
- 编写上传脚本(upload-videos.js)
const { google } = require('googleapis') const fs = require('fs') const path = require('path') async function uploadAllVideos() { const auth = new google.auth.GoogleAuth({ credentials: require('./google-credentials.json'), scopes: ['https://www.googleapis.com/auth/drive.file'] }) const drive = google.drive({ version: 'v3', auth }) const videosDir = path.join(__dirname, 'cypress', 'videos') // 读取视频目录下所有MP4文件 const videoFiles = fs.readdirSync(videosDir).filter(file => file.endsWith('.mp4')) for (const file of videoFiles) { const videoPath = path.join(videosDir, file) const uploadResult = await drive.files.create({ resource: { name: file, parents: ['替换为你的Drive文件夹ID'] }, media: { mimeType: 'video/mp4', body: fs.createReadStream(videoPath) }, fields: 'webViewLink' }) console.log(`${file} 上传完成:${uploadResult.data.webViewLink}`) } } uploadAllVideos().catch(err => console.error('上传失败:', err))
- 修改package.json脚本
{ "scripts": { "test": "cypress run && node upload-videos.js" } }
必要准备工作
- 登录Google Cloud控制台,创建项目并启用Google Drive API
- 创建服务账号,下载密钥JSON文件(即上述代码中的
google-credentials.json) - 将服务账号的邮箱地址,分享给目标Drive文件夹(赋予编辑权限)
内容的提问来源于stack exchange,提问作者noobr23
相关产品推荐
相关产品推荐

