运行Mocha测试时allure.addAttachment is not a function错误的解决方法
解决"allure.addAttachment is not a function"错误
错误原因
你直接require('mocha-allure-reporter')获取的对象并不提供addAttachment方法,这个模块是作为Mocha的报告器使用的,不是用来直接调用Allure API的。
正确解决方案(推荐使用allure-mocha)
1. 替换依赖包
卸载旧的mocha-allure-reporter,安装官方维护的适配Mocha的Allure插件及命令行工具:
npm uninstall mocha-allure-reporter npm install --save-dev allure-mocha allure-commandline
2. 修改测试代码
不需要直接require Allure模块,而是通过测试用例的上下文this.allure调用API。修改测试用例里的附件添加部分:
// 移除无效的引用:const allure = require('mocha-allure-reporter'); // ... 其他原有代码保持不变 ... it("test",async function(){ this.timeout(30000); await delay(3000) const ele = await page.$("#scandocument"); await ele.click(); await delay(3000); const mainContainer = await page.$("#dwtcontrolContainer"); await mainContainer.screenshot({path:'./Images/TempImages/testCamera.png'}); const num1 = await compareImages("./Images/TempImages/testCamera.png",'./Images/ExpectedImages/testCamera.png','./Images/DiffImages/diff_testCamera.png'); console.log(num1); const attachment1 = fs.readFileSync('./Images/TempImages/testCamera.png'); const attachment2 = fs.readFileSync('./Images/ExpectedImages/testCamera.png') const attachment3= fs.readFileSync('./Images/DiffImages/diff_testCamera.png') // 替换为上下文内的allure对象调用方法 this.allure.addAttachment('Screenshot',attachment1, 'image/png'); this.allure.addAttachment('ExpectedImage',attachment2, 'image/png'); this.allure.addAttachment('DiffImage', attachment3,'image/png'); assert.equal(num1,0); })
注意:测试用例的回调必须用
function而不是箭头函数,否则无法获取到包含allure对象的Mocha上下文。
3. 运行测试并生成报告
用指定报告器的方式运行Mocha测试:
mocha 你的测试文件路径.js --reporter allure-mocha
测试完成后生成并打开Allure报告:
npx allure generate allure-results --clean && npx allure open
额外注意事项
- 确保代码中已引入必要依赖:
const puppeteer = require('puppeteer'); const fs = require('fs'); const assert = require('assert'); // 若未定义delay函数,需补充 function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
compareImages函数需确保已正确定义或引入,否则会引发新的错误。
内容的提问来源于stack exchange,提问作者user19920223
相关产品推荐
相关产品推荐

