2012-04-10 36 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"); 
    }; 
}); 

,那麼你將能夠使引用它在你的規格文件