我需要使用 mocha-phantomjs 测试我的 Node js 应用程序。我已尝试使用以下代码来测试该应用程序,但收到错误“ReferenceError:找不到变量:require”。如何解决此问题。
测试.html
<html>
<head>
<title> 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/should/lib/should.js"></script>
<script>
mocha.ui('bdd');
mocha.reporter('html');
</script>
<script src="test.js"></script>
<script>
if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
else { mocha.run(); }
</script>
</body>
</html>
测试.js
var module=require('../lib/requiredModule');
var should = require('chai').should();
describe('Testing',function(){
it('Save Data',function(){
module.save(content,function(err,res){
should.not.exist(err);
});
});
});
当将 html 文件作为 mocha-phantomjs test/test.html 运行时,我收到错误为
ReferenceError: Can't find variable: require
最佳答案
所以,我认为您的问题是通过测试运行程序运行测试基本上就像在客户端一样运行它们。因此,它将无法找到您的 native Node 模块(例如 require)。您可以尝试加载require.js直接进入。或者,只需使用
<script src="../node_modules/chai/chai.js"></script>
<script>
mocha.ui('bdd');
mocha.reporter('html');
var should = chai.should; // This will give you access to chai should.
</script>
所以你不需要要求任何你需要的东西。再次,想象一下您正在客户端执行所有操作。
关于node.js - 如何使用 mocha-phantomjs 测试 Node js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16536357/