grunt contrib茉莉花罐';找不到PhantomJSAPI?

grunt contrib茉莉花罐';找不到PhantomJSAPI?,phantomjs,gruntjs,Phantomjs,Gruntjs,PhantomJSAPI声称允许通过标准require接口访问“fs”和其他一些内置commonJS模块。grunt contrib jasmine声称使用phantomJS运行所有规范。但是当我使用grunt contrib jasmine时,require方法似乎不可用 fs = require('fs') describe 'DesignService', -> it 'test loadFromJSON', -> jsonFile = fs.read("res

PhantomJSAPI声称允许通过标准require接口访问“fs”和其他一些内置commonJS模块。grunt contrib jasmine声称使用phantomJS运行所有规范。但是当我使用grunt contrib jasmine时,require方法似乎不可用

fs = require('fs')
describe 'DesignService',  ->
  it 'test loadFromJSON',  ->
    jsonFile = fs.read("resources/sample_pole.json")
给我一个错误:

 ReferenceError: Can't find variable: require at
>> target/spec/Spec.js:3 
我做错了什么

如果不清楚,我将从coffeescript编译,然后将grunt contrib jasmine指向编译的输出。其他规格都运行正常。

原因
require
方法仅在服务器端(Nodejs/PhantomJS)可用,但所有jasmine测试(spec)都在客户端执行

可能的解决办法 您可以在
helpers
文件夹中创建一个JavaScript文件,内容如下:

window.jsonFile = { some : json_object }
并在spec文件中使用
jsonFile
引用

解释 根据描述:

PhantomJS是一个无头WebKit,可使用JavaScript API编写脚本

从描述:

无头运行茉莉花规格通过幻影


grunt contrib jasmine
正在自动创建包含所有用户规范的
\u SpecRunner.html
文件(参见下面的示例),并将其传递给PhantomJS。PhantomJS是一个单独的可执行文件,它在Nodejs中仅包装为一个包。这是从页面下载的相同可执行文件

最后执行这一行:
\node\u modules\grunt contrib jasmine\node\u modules\grunt lib phantomjs\node\u modules\phantomjs\phantomjs\lib\phantomjs\node\grunt contrib jasmine\node\u modules\grunt lib phantomjs\main.js.\\u SpecRunner.html
。 这里的
main.js
文件用于打开页面并绑定抛出到grunt日志的警报(
alert(jsonString)

因此PhantomJSAPI在
main.js
中可用,但在
\u SpecRunner.html
和jasmine spec文件中不可用。

结果与使用浏览器打开的
\u SpecRunner.html
相同,只是jasmine reporter会截取所有消息并显示在屏幕上

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Jasmine Spec Runner</title>

  <link rel="stylesheet" type="text/css" href=".grunt/grunt-contrib-jasmine/jasmine.css">

  <!-- Jasmine test suite -->
  <script src="./.grunt/grunt-contrib-jasmine/jasmine.js"></script>
  <script src="./.grunt/grunt-contrib-jasmine/jasmine-html.js"></script>

  <!-- Some vendor libraries -->
  <script src="./test/vendor/jquery.js"></script>

  <!-- Some helpers -->
  <script src="./test/helpers/ts.js"></script>

  <!-- Your spec files -->
  <script src="./test/main_spec.js"></script>

  <!-- Jasmine reporter that displays the result-->    
  <script src="./.grunt/grunt-contrib-jasmine/reporter.js"></script>  
  <script src="./.grunt/grunt-contrib-jasmine/jasmine-helper.js"></script>
</head>
<body>
</body>
</html>

茉莉花跑步者

您是说PhantomJSAPI可用于使用Phantom的节点包,但不能从Phantom中运行的脚本中获得。对吗?我之前解释过,Phantom在他们的JS引擎中添加了对require/fs/etc的支持,以简化测试。我将尝试helper fix.PhantomJS是一个单独的可执行文件,在Nodejs paskage中它只是被包装的。您可以在
\node\u modules\grunt contrib jasmine\node\u modules\grunt lib phantomjs\node\u modules\phantomjs\lib\phantomjs
中检查它,这与您从phantomjs.og页面下载的包相同。您可以想象,最后执行这一行:
phantomjs jasmine.js./\u SpecRunner.html
,因此phantomjs API在
jasmine.js
中可用,但在
\u SpecRunner.html
中不可用。啊,我明白了。谢谢。这里有一个小例子,如何编写模块化测试并使用phantomjs进行测试,希望它对您有用。