Mocha运行报错TypeError: Describe is not a function及同步调试测试问题
解决Mocha的TypeError: Describe is not a function及调试测试的方法
一、修复TypeError: Describe is not a function错误
这个错误核心原因是你手动导入Mocha测试钩子的方式不对,再加上代码里的一些细节问题,一步步来解决:
1. 移除不必要的手动导入
Mocha在运行测试时,会自动把describe、it、before这些测试相关函数暴露到全局作用域,完全不需要你通过require('mocha').describe的方式手动导入。直接删掉这行代码就行:
var describe = require ('mocha').describe; var it = require ('mocha').it; var before = require ('mocha').before;
2. 修正代码里的其他问题
你的测试代码还有几个小bug,不修正的话即使解决了describe的错误,测试也会失败:
- 拼写错误:
getResonse少了一个p,应该是getResponse - 变量名混乱:
ApI和API大小写混用,rep未定义就直接使用 - 异步测试未收尾:如果你的
getResponse是同步方法,直接去掉done参数即可;如果是异步方法,必须调用done()通知Mocha测试完成
修正后的代码示例:
var expect = require('chai').expect; var assert = require('chai').assert; var API = require('C:/Users/Niku/Desktop/api/api/controllers/API.js'); // 假设Id、key、List、api_jwt、KPOAuthAPI这些变量已提前定义 describe('getResponse tests', function() { it('getResponse first from server and then from local', function() { // 同步测试移除done参数 var apiInstance = new API(Id, key, List); var rep1 = apiInstance.getResponse(); assert.isNotEmpty(rep1); console.log("1" + api_jwt); assert.deepEqual(rep1, KPOAuthAPI.getResponse()); }); describe('getResponse from server after Timeout', function() { it('getResponse should return the rep from local', function() { // 同步测试移除done参数 var apiInstance = new API(Id, key, List); var rep1 = apiInstance.getResponse(); // 确保rep是之前保存的服务器返回值,比如可以在before钩子中提前获取 assert.notEqual(rep, rep1); }); }); });
二、以调试模式同步运行测试代码
这里给你三种常用的调试方式,按需选择:
1. 命令行用Node原生调试器
如果是全局安装的Mocha,直接运行:
node inspect $(which mocha) 你的测试文件路径.js
如果是项目本地安装的Mocha,用:
node inspect node_modules/mocha/bin/mocha 你的测试文件路径.js
进入调试模式后,用n执行下一步,c继续运行,repl可以实时查看变量值。
2. 用Mocha自带的调试参数
Mocha支持直接通过--inspect-brk启动调试,操作更简单:
# 全局Mocha mocha --inspect-brk 你的测试文件路径.js # 本地Mocha npx mocha --inspect-brk 你的测试文件路径.js
运行后打开Chrome浏览器,输入chrome://inspect,配置添加本地9229端口(默认调试端口),就能在Chrome DevTools里设置断点、查看变量,调试体验很好。
3. VS Code可视化调试
在项目根目录创建.vscode/launch.json文件,添加以下配置:
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Mocha Tests", "program": "${workspaceFolder}/node_modules/mocha/bin/mocha", "args": [ "你的测试文件路径.js" ], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ] }
然后点击VS Code左侧的调试按钮,选择"Mocha Tests"就能启动可视化调试了。
内容的提问来源于stack exchange,提问作者MANOJ
相关产品推荐
相关产品推荐

