node.js - unit - vscode describe is not defined
ReferenceError:describe未定义NodeJs (5)
我试图定义一些端点并使用
nodejs
进行测试。
在
server.js
我有:
var express = require('express');
var func1 = require('./func1.js');
var port = 8080;
var server = express();
server.configure(function(){
server.use(express.bodyParser());
});
server.post('/testend/', func1.testend);
并在
func1.js
:
var testend = function(req, res) {
serialPort.write("1", function(err, results) {
serialPort.write("2" + "\n", function(err, results) {
});
});
});
exports.testend = testend;
现在在
test.js
我试图使用这个端点:
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var http = require('http');
var app = require('./../server.js');
var port = 8080;
describe('Account', function() {
var url = "http://localhost:" + port.toString();
it('test starts', function(done) {
request(url).post('/testend/')
// end handles the response
.end(function(err, res) {
if (err) {
throw err;
}
res.body.error.should.type('string');
done();
});
});
});
但是,当我运行
node test.js
我收到此错误:
describe('Account', function() { ^ ReferenceError: describe is not defined at Object. (/test/test.js:9:1) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:906:3
我该如何解决这个问题?
OP询问从
node
运行而不是从
mocha
运行。
这是一个非常常见的用例,请参阅
以编程方式使用Mocha
这是注入描述和我的测试。
mocha.ui('bdd').run(function (failures) {
process.on('exit', function () {
process.exit(failures);
});
});
我在文档中尝试了
tdd
,但这没有用,但是bdd工作了。
你也可以这样做:
var mocha = require('mocha')
var describe = mocha.describe
var it = mocha.it
var assert = require('chai').assert
describe('#indexOf()', function() {
it('should return -1 when not present', function() {
assert.equal([1,2,3].indexOf(4), -1)
})
})
参考: http://mochajs.org/#require : http://mochajs.org/#require
假设您正在通过
mocha
进行测试,则必须使用
mocha
命令而不是
node
可执行文件来运行测试。
所以如果你还没有,请确保你做
npm install mocha -g
。
然后在项目的根目录中运行
mocha
。
要在不全局安装Mocha的情况下使用node / npm运行测试,您可以执行以下操作:
•在本地安装Mocha到您的项目(
npm install mocha --save-dev
)
•可选择安装断言库(
npm install chai --save-dev
)
•在
package.json
,添加
scripts
部分并定位mocha二进制文件
"scripts": {
"test": "node ./node_modules/mocha/bin/mocha"
}
•将spec文件放在根目录中名为
/test
的目录中
•在spec文件中,导入断言库
var expect = require('chai').expect;
•您不需要导入mocha,运行
mocha.setup
或调用
mocha.run()
•然后从项目根目录运行脚本:
npm test