2012-04-10 37 views
9

这个问题很可能是基于我以前没有使用node.js的经验,但我希望jasmine-node只是让我从命令行运行我的茉莉花规格。为什么茉莉花节点没有拿起我的帮手脚本?

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上明显。任何意见或帮助将不胜感激!

谢谢!

回答

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; 

,然后改变你的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

+0

非常感谢!所以...要贪婪,可以以某种方式转换为运行在jasmine-node上并使用SpecRunner.html?当使用html版本时,我得到“出口未定义”和“需求未定义”。 – Hoopes 2012-04-10 18:45:26

+0

我没有用过它,但我认为http://requirejs.org/会有所帮助。 – 2012-04-10 22:34:18

+1

或者,如果(需要){... [加载文件] ...}'和'如果(!出口){var exports = window.helpers = {}}'',您可以做一些简单的解决方案 – 2012-04-10 22:38:04

2

你不一定需要在规范(测试)你的助手脚本,如果你有作为茉莉的配置文件:在助手/文件夹

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

一切都将在规格文件之前运行。在助手文件中有这样的东西来包含你的功能。

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

,那么你将能够使引用它在你的规格文件