【问题标题】:why is jasmine-node not picking up my helper script?为什么 jasmine-node 没有选择我的帮助脚本?
【发布时间】:2012-04-22 08:06:46
【问题描述】:

这个问题可能是因为我以前缺乏使用 node.js 的经验,但我希望 jasmine-node 能让我从命令行运行我的 jasmine 规范。

TestHelper.js:

var helper_func = function() {
    console.log("IN HELPER FUNC");
};

my_test.spec.js:

describe ('Example Test', function() {
  it ('should use the helper function', function() {
    helper_func();
    expect(true).toBe(true);
  }); 
});

这是目录中仅有的两个文件。然后,当我这样做时:

jasmine-node .

我明白了

ReferenceError: helper_func is not defined

我确信这个问题的答案很简单,但我没有在 github 上找到任何超级简单的介绍或任何明显的内容。任何建议或帮助将不胜感激!

谢谢!

【问题讨论】:

    标签: javascript unit-testing testing node.js jasmine


    【解决方案1】:

    如果您的 jasmine 配置为:

    {
      "spec_dir": "spec",
      "spec_files": [
        "**/*[sS]pec.js"
      ],
      "helpers": [
        "helpers/**/*.js"
      ],
      "stopSpecOnExpectationFailure": false,
      "random": false
    }
    

    helpers/ 文件夹中的所有内容都将在 Spec 文件之前运行。在帮助文件中有这样的东西来包含你的功能。

    beforeAll(function(){
      this.helper_func = function() {
      console.log("IN HELPER FUNC");
      };
    });
    

    然后您就可以在您的规范文件中引用它

    【讨论】:

    • 我想知道helpers 究竟是什么以及如何使用它们。我以前使用module.exportsrequire 来处理utils 文件。 Jasmine 文档仅显示如何在配置文件中设置帮助程序路径。感谢您的澄清,帮助者似乎非常......乐于助人:)
    【解决方案2】:

    在节点中,所有内容都被命名为它的 js 文件。要使其他文件可以调用该函数,请将 TestHelper.js 更改为如下所示:

    var helper_func = function() {
        console.log("IN HELPER FUNC");
    };
    // exports is the "magic" variable that other files can read
    exports.helper_func = helper_func;
    

    然后将您的 my_test.spec.js 更改为如下所示:

    // include the helpers and get a reference to it's exports variable
    var helpers = require('./TestHelpers');
    
    describe ('Example Test', function() {
      it ('should use the helper function', function() {
        helpers.helper_func(); // note the change here too
        expect(true).toBe(true);
      }); 
    });
    

    最后,我相信jasmine-node . 会按顺序运行目录中的每个文件——但您不需要运行帮助程序。相反,您可以将它们移动到不同的目录(并将require() 中的./ 更改为正确的路径),或者您可以只运行jasmine-node *.spec.js

    【讨论】:

    • 非常感谢!所以......为了贪婪,这是否可以以某种方式转换为在 jasmine-node 上运行并使用 SpecRunner.html?使用 html 版本时,我得到“未定义导出”和“未定义要求”。
    • 或者,你可以做一些事情 if(require){...[load files]...}` 和 if(!exports) { var exports = window.helpers = {} } 一个简单的解决方案
    • 我整天都在寻找这个答案。我不想将 Ruby 与 Jasmine 一起使用。非常感谢。
    • Jasmine 在没有 jasmine-node 的情况下与 node.js 一起工作得很好。虽然它更喜欢module.exports
    • 是的,现在是这样。不过,我认为 2 多年前的情况并非如此。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2013-02-12
    相关资源
    最近更新 更多