Javascript PhantomJS中的RequireJS错误,而不是Chrome/FireFox中的错误

Javascript PhantomJS中的RequireJS错误,而不是Chrome/FireFox中的错误,javascript,requirejs,phantomjs,Javascript,Requirejs,Phantomjs,我在同一目录中有两个文件: <html> <head> <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script> <script type="text/javascript"> require(["fakeTest"], function

我在同一目录中有两个文件:

<html>
<head>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script>
    <script type="text/javascript">
        require(["fakeTest"], function () {});
    </script>
</head>
<body>
</body>
</html>
如果我在Chrome/FireFox中运行这个,我会得到我所期望的。如果我尝试使用以下命令从CMD运行:

phantomjs --remote-debugger-port=9000 testFile.html
我得到一个错误:

错误:找不到模块“fakeTest”

phantomjs://bootstrap.js:299 在需要时
phantomjs://bootstrap.js:263 急需


我尝试过最新的PhantomJS和旧版本,RequireJS也是如此。我已经在谷歌搜索过了,但没有找到任何解决方案。我让其他人在他们的电脑上试过,他们也看到了同样的问题。我已经尽可能地简化了文件,现在还不确定还有什么可以尝试。

如果您直接运行PhantomJS,那么您需要创建一个脚本来加载页面。请参见下面的示例。也就是说,如果您正试图测试您的网页,那么有一些设计用于PhantomJS。这些框架负责在运行测试时加载HTML、脚本和其他资源的细节。就个人而言,我使用with来运行单元测试

如果您试图直接运行PhatomJS,则需要创建一个脚本来打开HTML页面。在下面的简单示例run.js中,打开“testFile.html”页面,并打印页面标题。然后设置100毫秒超时,再次打印标题并退出

var page = require('webpage').create();

page.open('testFile.html', function(status) {
  var title = page.evaluate(function() {
    return document.title;
  });
  console.log('Page title is ' + title);
  setTimeout(function () {
    var title  = page.evaluate(function () {
      return document.title;
    });
    console.log('Page title is ' + title);
    phantom.exit()
  }, 100);
});
下面是运行该命令的输出示例:

phantomjs run.js 
Page title is Original Title
Page title is Title Updated
超时的原因是AMD模块是异步加载的,您需要在run.js脚本中构建一种方法来考虑AMD模块的异步特性。我强烈建议使用与RequireJS集成的现有测试运行程序之一,而不是重新发明轮子

要查看此操作,请将testFile.html修改为:

<html>
<head>
    <title>Original Title</title>
    <script type="text/javascript"
     src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js">    
    </script>
    <script type="text/javascript">
        require(["fakeTest"], function () {});
    </script>
</head>
<body>
</body>
</html>
<html>
<head>
    <title>Original Title</title>
    <script type="text/javascript"
     src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js">    
    </script>
    <script type="text/javascript">
        require(["fakeTest"], function () {});
    </script>
</head>
<body>
</body>
</html>
define(["require", "exports"], function (require, exports) {
  document.title = 'Title Updated';
});