PhantomJS API声称允许通过标准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指向编译的输出 . 其他规格都运行正常 .
1 回答
原因
require
方法仅在服务器端(Nodejs / PhantomJS)可用,但所有jasmine测试(规范)都在客户端执行 .可能的解决方案
您可以在
helpers
文件夹中创建一个JavaScript文件,其内容如下:并在spec文件中使用
jsonFile
引用 .解释
来自PhantomJS描述:
来自grunt-contrib-jasmine描述:
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
文件是打开页面并绑定抛出到grunt日志记录的警报(alert(jsonString)
) .So PhantomJS API is available in main.js, but not in _SpecRunner.html and jasmine spec files.
结果与浏览器打开
_SpecRunner.html
相同,但所有消息都将被jasmine记者拦截并显示在屏幕上 .