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/