【问题标题】:How to import other javascript module in PhantomJS or CasperJS如何在 PhantomJS 或 CasperJS 中导入其他 javascript 模块
【发布时间】:2013-07-16 10:14:18
【问题描述】:

我正在尝试使用 CasperJS 构建功能测试。 caseperjs 由后端测试套件使用以下命令运行:

PHANTOMJS_EXECUTABLE=../client/node_modules/phantomjs/bin/phantomjs  ../client/ext_modules/casperjs/bin/casperjs test ../client/test/functional/init.coffee

init.coffee 我想导入/包含其他模块(文件),它就在它旁边。怎么做?

以下不起作用:

require("user")

我只想从其他文件中获取内容到 init.coffee

【问题讨论】:

    标签: javascript coffeescript phantomjs casperjs


    【解决方案1】:

    在尝试了一些其他建议(每个建议都希望在其相应环境的上下文中工作)之后,找到这个解决方案:

    phantom.page.injectJs( 'script.js');
    

    【讨论】:

    • 如果文件不存在,是否应该静默失败?
    • Soz,没试过。期待它不会默默地失败。
    【解决方案2】:

    从 1.1 开始,CasperJS 依赖于 PhantomJS 的原生 require():
    https://groups.google.com/forum/#!topic/phantomjs/0-DYnNn_6Bs

    注入依赖

    在注入附加模块时,CasperJS 会查找相对于 cur 目录的路径 (我们运行 casperjs 命令的地方) 我们可以使用clientScripts 选项注入依赖。但是注入的依赖项不能 使用require“全局”。它们会立即注入到加载的每个页面。

    casper.options.clientScripts = ["path/relative/to/cur/dir"]
    

    我们也可以使用命令行参数注入模块:

    casperjs test --includes=foo.js,bar.js path/to/the/test/file
    

    使用要求

    要导入用户模块,请使用:

    require "./user-module.coffee"
    

    然后在用户模块中你也可以使用require。使用要求路径已解决 相对于当前文件(调用 require 的地方)。
    如果在用户模块中要导入 casper 库,则需要 patch require, 检查:https://casperjs.readthedocs.org/en/latest/writing_modules.html

    【讨论】:

      【解决方案3】:

      文档中有a section about that

      var require = patchRequire(global.require);
      require('./user');
      

      在您的情况下,您应该使用 global.require,因为您使用的是 CoffeeScript。

      【讨论】:

      • Doc 说 patchRequire 被使用 为了允许要求 casper 模块使用它们的全名,例如。 require('casper') 在用户模块中。
      • 见后面的例子。也许我误解了文档,我没有尝试过。
      • 是的,我看到了。谢谢你!我正在准备这个问题的答案。
      猜你喜欢
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2018-08-04
      相关资源
      最近更新 更多