node.js - 如何使用 mocha-phantomjs 测试 Node js 应用程序

标签 node.js phantomjs mocha.js chai

我需要使用 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/

相关文章:

javascript - 空数组和排序推送的键 JavaScript

javascript - 如何使用phantomjs保存 "while"中的文件?

javascript - 如何使用 CasperJS 通过 id 提取输入值?

java - PhantomJS 版本与 Selenium 的兼容性

javascript - Protractor - 查找所有元素和找到的元素的循环长度,然后单击按钮

javascript - Webpack 相当于已包含模块的 browserify shiming(global)

javascript - Node/Javascript 仅发送更改的值

node.js - 我应该从 Vows 切换到 Mocha 吗?

javascript - 使用 Mocha 测试 ES 2015 模块

node.js - 我将如何测试在 express 中使用 mocha/chai/superagent 发送路由?