node js chai mocha“ReferenceError:找不到变量require”
问题描述:
我正在使用grunt,mocha和chai来运行基本的单元测试。我的单元测试看起来如下node js chai mocha“ReferenceError:找不到变量require”
describe('SPSearchConnection', function() {
describe('#performSearch()', function() {
it('should return zero or more results', function() {
var spSearchConnect = require('../index');
alert(spSearchConnect);
chai.assert.equal(-1, [1, 2, 3].indexOf(5));
});
});
});
现在,当我使用咕噜“咕噜”我收到以下错误运行测试:
ReferenceError: Can't find variable: require
我gruntfile.js看起来是这样的:
// Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Mocha
mocha: {
all: {
src: ['tests/testrunner.html'],
},
options: {
run: true
}
}
});
// Load grunt mocha task
grunt.loadNpmTasks('grunt-mocha');
grunt.registerTask('default', ['mocha']);
};
我testrunner.html文件看起来像这样:
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script>
mocha.setup('bdd')
mocha.reporter('html');
</script>
<!-- Tests -->
<script src="tests.js"></script>
<!-- Tests -->
<script></script>
<script>
// Only tests run in real browser, injected script run if options.run == true
if (navigator.userAgent.indexOf('PhantomJS') < 0) {
mocha.run();
}
</script>
</body>
</html>
有人能告诉我如何解决这个问题吗?
答
单元测试有行require('../index')
,但问题是,你的测试是要在浏览器环境中,不具有天然require
功能(因此ReferenceError
)运行。如果您需要包含一个单独的文件,您可以使用"requirejs"库(其中为用于浏览器)。或者您可以在HTML文件中使用<script>
标签?或者可能只是一个简单的Ajax调用...
使用“requirejs”我应该包括什么以使require功能可用?你能给我一个工作样本吗? – user3547774 2015-02-10 04:16:31