如何解决Selenium+Mocha执行npm test时的npm ERR! Test failed报错?
问题描述
我用JavaScript编写的Selenium测试脚本在其他系统可正常运行,但在当前Ubuntu环境执行npm test时持续报错,错误信息如下:
✖ ERROR: Error: Not supported at Object.exports.doImport (/home/sahil/frontend-selenium-testing/node_modules/mocha/lib/nodejs/esm-utils.js:35:41) at formattedImport (/home/sahil/frontend-selenium-testing/node_modules/mocha/lib/nodejs/esm-utils.js:32:18) at exports.requireOrImport (/home/sahil/frontend-selenium-testing/node_modules/mocha/lib/nodejs/esm-utils.js:42:34) at exports.handleRequires (/home/sahil/frontend-selenium-testing/node_modules/mocha/lib/cli/run-helpers.js:94:34) at process._tickCallback (internal/process/next_tick.js:68:7) at Function.Module.runMain (internal/modules/cjs/loader.js:834:11) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) npm ERR! Test failed. See above for more details.
我的package.json配置:
{ "name": "selenium", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "mocha --no-timeouts --reporter mochawesome --require mochawesome/register" }, "author": "", "license": "ISC", "dependencies": { "chai": "^4.3.7", "mocha": "^10.2.0", "mochawesome": "^7.1.3", "selenium-webdriver": "^4.7.1" } }
我导入包的方式:
const { Builder, By, Key, until } = require("selenium-webdriver") const assert = require('assert') const should = require('chai').should() const { monitorTaskTestFunc } = require('./monitorTask') const { resolve } = require("path") const { loginTest } = require("./loginTest")
我已完成Ubuntu环境下ChromeDriver的Path配置。
错误根源
报错栈指向Mocha的ES模块处理工具,结合你的配置(使用CommonJS的require语法、Mocha 10.x + Mochawesome 7.x组合),问题大概率是Mochawesome注册方式过时或版本兼容性冲突导致。
可行解决方案
1. 精简测试命令(优先尝试)
Mochawesome 7.x版本已无需通过--require mochawesome/register注册,直接指定--reporter mochawesome即可生成测试报告。修改package.json中的scripts字段:
"scripts": { "test": "mocha --no-timeouts --reporter mochawesome" }
2. 降级Mocha版本
如果方案1无效,Mocha 10.x对ES模块的处理逻辑改动较大,与Mochawesome 7.x存在兼容风险,可降级到稳定兼容的Mocha 9.x版本:
# 卸载当前Mocha版本 npm uninstall mocha # 安装兼容版本 npm install mocha@9.2.2 --save-dev
3. 检查Node.js版本
Mocha 10.x要求Node.js版本至少为v14.17.0,过低版本会导致ES模块处理异常。执行以下命令查看当前Node.js版本:
node -v
若版本低于要求,升级到Node.js LTS版本即可。
4. 确认项目模块格式
如果你的package.json中存在"type": "module"字段,会强制Node.js以ES模块模式处理文件,与你使用的require(CommonJS语法)冲突。检查并移除该字段(如果存在):
// 删除这一行 "type": "module"
验证修改
完成上述调整后,重新执行测试命令验证:
npm test
内容的提问来源于stack exchange,提问作者sahil baranwal

