phantomjs - grunt-contrib-jasmine 找不到 PhantomJS API?

标签 phantomjs gruntjs

PhantomJS API 声称允许通过标准 require 接口(interface)访问“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 测试(规范)都在客户端执行。

可能的解决方案

您可以在 helpers 中创建一个 JavaScript 文件文件夹内容如下:

window.jsonFile = { some : json_object }

并使用 jsonFile在您的规范文件中引用。

解释

来自 PhantomJS描述:

PhantomJS is a headless WebKit scriptable with a JavaScript API.



来自 grunt-contrib-jasmine描述:

Run jasmine specs headlessly through PhantomJS.


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

最后这一行被执行:.\node_modules\grunt-contrib-jasmine\node_modules\grunt-lib-phantomjs\node_modules\phantomjs\lib\phantom\phantomjs .\node_modules\grunt-contrib-jasmine\node_modules\grunt-lib-phantomjs\phantomjs\main.js .\_SpecRunner.html .
这里main.js文件是打开页面并绑定(bind)警报(alert(jsonString)),这些警报会被抛出到 grunt 日志中。

所以 PhantomJS API 在 main.js 中可用,但不在 _SpecRunner.html 中和 Jasmine 规范文件。

结果和打开_SpecRunner.html一样使用浏览器,除了所有消息都会被 Jasmine 记者截获并显示在屏幕上。
<!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>

关于phantomjs - grunt-contrib-jasmine 找不到 PhantomJS API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17677654/

相关文章:

css - 在 CasperJS 中使用 CSS3 选择器按文本选择元素

memory-leaks - phantomjs 没有关闭并留下孤立进程

html - 使用 ghostscript 缩小 PDF 会导致图像不对齐

node.js - 通过 localhost :port on virtual machine 访问 node.js/grunt 服务器

gruntjs - 为具有多个点的文件配置 Grunt 文件名匹配

javascript - 访问并填充特定的 div 元素

css - JSPM 是如何处理 CSS 文件的?

visual-studio-2010 - 从 Visual Studio 生成后事件命令行运行 Grunt

node.js - Grunt - 压缩和包含带有时间戳的 Assets

python - 无法通过 Selenium 在 python 中运行 PhantomJS