Nodejs 我安装了mocha模块,为何出现`ReferenceError: describe is not defined`

Nodejs 我安装了mocha模块,为何出现ReferenceError: describe is not defined

var assert = require(“assert”);
describe(‘Array’, function(){
describe(’#indexOf()’, function(){
it(‘should return -1 when the value is not present’, function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
});

我安装了mocha模块,为何出现ReferenceError: describe is not defined 怎么回事??


8 回复

当你在 Node.js 中使用 Mocha 进行测试时,如果遇到 ReferenceError: describe is not defined 错误,通常是因为你没有正确地运行测试脚本。Mocha 需要在特定的环境中才能识别 describe, it 等函数。

以下是一个示例,展示如何正确设置和运行你的测试脚本:

示例代码

假设你已经安装了 Mocha 模块(如果没有安装,可以通过 npm install mocha --save-dev 来安装)。

测试文件 (test.js)

var assert = require("assert");

describe('Array', function() {
    describe('#indexOf()', function() {
        it('should return -1 when the value is not present', function() {
            assert.equal(-1, [1,2,3].indexOf(5));
            assert.equal(-1, [1,2,3].indexOf(0));
        });
    });
});

如何运行测试

在命令行中,你需要通过 Mocha 来运行你的测试脚本。可以使用以下命令来运行测试:

npx mocha test.js

或者,如果你在 package.json 文件中配置了测试脚本,你可以直接运行:

{
  "scripts": {
    "test": "mocha test.js"
  }
}

然后运行:

npm test

解释

  • 环境问题describeit 是 Mocha 提供的全局函数,但只有在 Mocha 的环境中才会被定义。如果你直接运行 node test.js 而不是通过 Mocha,这些函数不会被定义。

  • 正确的运行方式:确保你通过 Mocha 运行测试脚本,而不是直接用 Node.js 运行。这会确保 Mocha 正确加载并执行你的测试用例。

通过以上步骤,你应该能够解决 ReferenceError: describe is not defined 的问题,并成功运行你的测试。


全局安装 mocha test.js

请问你你这个问题搞定了没? 我现在也遇见同样的问题了

确定npm install --save mocha 成功了?

mark一下,我使用的是webstorm,遇到了同样的问题,解决方法是使用mocha指定去执行而不是使用node直接执行

我是windows系统 npm install -g mocha 成功了 node app.test 提示 describe is not defined mocha app.test 提示 ‘mocha’ 不是内部或外部命令,也不是可运行的程序或批处理文件。

呃,使用Visual Studio Code,6楼正解,使用 mocha test.js 执行,不会报错 QQ图片20180702161331.png

你在使用Mocha进行测试时遇到 ReferenceError: describe is not defined 的错误,是因为你尝试直接运行一个 Mocha 测试文件,而不是通过 Mocha 命令行工具来执行它。Mocha 提供的 describeit 等函数需要在 Mocha 的测试环境中才能被识别。

你需要通过命令行来运行你的测试文件。假设你的测试文件名为 test.js,你可以使用以下命令来运行:

mocha test.js

如果你的项目结构中有多个测试文件或目录,可以简化为:

mocha .

这将运行当前目录下的所有测试文件。

示例代码

确保你的文件以 .js 结尾,并且包含 Mocha 的典型结构。以下是一个完整的例子:

// test.js
var assert = require("assert");

describe('Array', function() {
    describe('#indexOf()', function() {
        it('should return -1 when the value is not present', function() {
            assert.equal(-1, [1,2,3].indexOf(5));
            assert.equal(-1, [1,2,3].indexOf(0));
        });
    });
});

然后,在命令行中运行:

mocha test.js

这样就可以正确识别并执行 describeit 函数了。

回到顶部