为什么jasmine-node没有拿起我的助手脚本?

Hoo*_*pes 10 javascript testing unit-testing node.js jasmine

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

TestHelper.js:

var helper_func = function() {
    console.log("IN HELPER FUNC");
};
Run Code Online (Sandbox Code Playgroud)

my_test.spec.js:

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

这些是目录中唯一的两个文件.然后,当我这样做时:

jasmine-node .
Run Code Online (Sandbox Code Playgroud)

我明白了

ReferenceError: helper_func is not defined
Run Code Online (Sandbox Code Playgroud)

我确信答案很容易,但我没有找到任何超级简单的介绍,或者github上的任何明显的介绍.任何建议或帮助将不胜感激!

谢谢!

Nat*_*dly 16

在节点中,所有内容都被命名为它的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;
Run Code Online (Sandbox Code Playgroud)

然后将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);
  }); 
});
Run Code Online (Sandbox Code Playgroud)

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

  • 或者,你可以只做一些 if(require){...[load files]...}` 和 `if(!exports) { var exports = window.helpers = {} }` 一个简单的解决方案 (2认同)
  • 我整天都在寻找这个答案.我不想将Ruby与Jasmine一起使用.非常感谢你. (2认同)