2013-05-07 92 views
63

我首先想說的是,我是RequireJS的新手,甚至是Jasmine的新手。獲取requirejs與Jasmine一起工作

我遇到了一些與SpecRunner有關的問題,需要JS。我一直在關注Uzi Kilon和Ben Nadel的教程(以及其他一些),他們幫助了一些人,但我仍然有一些問題。

看來,如果在測試中出現錯誤(我可以想到一個特別的類型錯誤),spec runner html會顯示。這告訴我,我在JavaScript中有一些問題。但是,在我解決這些錯誤之後,不再顯示HTML。 我無法讓測試運行器顯示。有人會發現我的代碼有問題會導致此問題?

這裏是我的目錄結構

Root 
|-> lib 
    |-> jasmine 
     |-> lib (contains all of the jasmine lib) 
     |-> spec 
     |-> src 
    |-> jquery (jquery js file) 
    |-> require (require js file) 
index.html (spec runner) specRunner.js 

這裏是SpecRunner(指數)HTML

<!doctype html> 
<html lang="en"> 
    <head> 
     <title>Javascript Tests</title> 

     <link rel="stylesheet" href="lib/jasmine/lib/jasmine.css"> 

     <script src="lib/jasmine/lib/jasmine.js"></script> 
     <script src="lib/jasmine/lib/jasmine-html.js"></script> 
     <script src="lib/jquery/jquery.js"></script> 
     <script data-main="specRunner" src="lib/require/require.js"></script> 

     <script> 
      require({ paths: { spec: "lib/jasmine/spec" } }, [ 
        // Pull in all your modules containing unit tests here. 
        "spec/notepadSpec" 
       ], function() { 
        jasmine.getEnv().addReporter(new jasmine.HtmlReporter()); 
        jasmine.getEnv().execute(); 
       }); 
     </script> 

    </head> 

<body> 
</body> 
</html> 

這裏是specRunner.js(配置)

require.config({ 
    urlArgs: 'cb=' + Math.random(), 
    paths: { 
     jquery: 'lib/jquery', 
     jasmine: 'lib/jasmine/lib/jasmine', 
     'jasmine-html': 'lib/jasmine/lib/jasmine-html', 
     spec: 'lib/jasmine/spec/' 
    }, 
    shim: { 
     jasmine: { 
      exports: 'jasmine' 
     }, 
     'jasmine-html': { 
      deps: ['jasmine'], 
      exports: 'jasmine' 
     } 
    } 
}); 

這裏有一個規範:

require(["../lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 
     expect(notepad.noteTitles()).toEqual(""); 


    }); 
}); 

記事本來源:

define(['lib/jasmine/src/note'], function (note) { 

    var notes = [ 
     new note('pick up the kids', 'dont forget to pick up the kids'), 
     new note('get milk', 'we need two gallons of milk') 
    ]; 


    return { 
     noteTitles: function() { 
      var val; 

      for (var i = 0, ii = notes.length; i < ii; i++) { 
       //alert(notes[i].title); 
       val += notes[i].title + ' '; 
      } 

      return val; 
     } 
    }; 
}); 

和NOTE源(JIC):

define(function(){ 
    var note = function(title, content) { 
     this.title = title; 
     this.content = content; 
    }; 

    return note; 
}); 

我已經確定的是,就應用程序而言,路徑是正確的。一旦我得到這個工作,我可以玩弄配置這些路徑,以便它不那麼難過。

+0

你能嘗試這個?在需求之外定義HtmlReported。只調用裏面執行。 var jasmineEnv = jasmine.getEnv(); jasmineEnv.addReporter(new jasmine.HtmlReporter()); require(['suites/aSpec.js'],function(spec){jsmineEnv.execute(); }); – basos 2013-05-11 11:39:20

+1

對於茉莉花2.0.0獨立,這個答案適合我: http://stackoverflow.com/questions/19240302/does-jasmine-2-0-really-not-work-with-require-js/20851265#20851265 – shaunsantacruz 2014-02-19 19:16:38

回答

55

我設法得到這個工作與一些試驗和錯誤。主要的問題是,當你寫的規格是不是要求您要創建,要使用定義:

原文:

require(["/lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 
     expect(notepad.noteTitles()).toEqual("pick up the kids get milk"); 


    }); 
}); 

工作:

define(["lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 

     it("something", function() { 

      expect(notepad.noteTitles()).toEqual("pick up the kids get milk "); 
     }); 

    }); 
}); 

在做了一些研究之後,很明顯的是,當使用RequireJS時,任何你想require()使用的東西都必須被包裝在一個define中(現在看來我覺得很明顯)。您可以看到,在specRunner.js文件中,在執行測試時使用了一個require(因此需要「定義」規格。

另一個問題是,在創建規範時,describe()和它()是必要的(不僅僅像我在發佈的例子中描述的那樣)。

原文:

describe("returns titles", function() { 
     expect(notepad.noteTitles()).toEqual("pick up the kids get milk"); 


    }); 

工作:

describe("returns titles", function() { 

     it("something", function() { 

      expect(notepad.noteTitles()).toEqual("pick up the kids get milk "); 
     }); 

    }); 

我也改變了圍繞在測試運行存在,但是這是一個重構,並沒有改變測試的結果。

同樣,這裏有文件和改變:

note.js:保持不變

notepad.js:保持不變

的index.html:

<!doctype html> 
<html lang="en"> 
    <head> 
     <title>Javascript Tests</title> 
     <link rel="stylesheet" href="lib/jasmine/lib/jasmine.css"> 
     <script data-main="specRunner" src="lib/require/require.js"></script> 
    </head> 

    <body> 
    </body> 
</html> 

個specRunner.js:

require.config({ 
    urlArgs: 'cb=' + Math.random(), 
    paths: { 
     jquery: 'lib/jquery', 
     'jasmine': 'lib/jasmine/lib/jasmine', 
     'jasmine-html': 'lib/jasmine/lib/jasmine-html', 
     spec: 'lib/jasmine/spec/' 
    }, 
    shim: { 
     jasmine: { 
      exports: 'jasmine' 
     }, 
     'jasmine-html': { 
      deps: ['jasmine'], 
      exports: 'jasmine' 
     } 
    } 
}); 


require(['jquery', 'jasmine-html'], function ($, jasmine) { 

    var jasmineEnv = jasmine.getEnv(); 
    jasmineEnv.updateInterval = 1000; 

    var htmlReporter = new jasmine.HtmlReporter(); 

    jasmineEnv.addReporter(htmlReporter); 

    jasmineEnv.specFilter = function (spec) { 
     return htmlReporter.specFilter(spec); 
    }; 

    var specs = []; 

    specs.push('lib/jasmine/spec/notepadSpec'); 



    $(function() { 
     require(specs, function (spec) { 
      jasmineEnv.execute(); 
     }); 
    }); 

}); 

notepadSpec.js:

define(["lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 

     it("something", function() { 

      expect(notepad.noteTitles()).toEqual("pick up the kids get milk"); 
     }); 

    }); 
}); 
+1

對於_的主要問題是,當您編寫規範時,它不是您要創建的要求,而是要使用define_。如果您使用require,您的測試有時可以正常工作,有時不會出現錯誤_no specs found_。 – 2013-12-30 22:37:24

12

剛剛添加該爲您使用的茉莉花2.0獨立的人誰的替代答案。我相信這也適用於茉莉花1.3,但異步語法是不同的,有點醜陋。

這是我修改SpecRunner.html文件:

<!DOCTYPE HTML> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Jasmine Spec Runner v2.0.0</title> 

    <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png"> 
    <link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css"> 

    <!-- 
    Notice that I just load Jasmine normally 
    -->  
    <script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script> 
    <script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script> 
    <script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script> 

    <!-- 
    Here we load require.js but we do not use data-main. Instead we will load the 
    the specs separately. In short we need to load the spec files synchronously for this 
    to work. 
    --> 
    <script type="text/javascript" src="js/vendor/require.min.js"></script> 

    <!-- 
    I put my require js config inline for simplicity 
    --> 
    <script type="text/javascript"> 
    require.config({ 
     baseUrl: 'js', 
     shim: { 
      'underscore': { 
       exports: '_' 
      }, 
      'react': { 
       exports: 'React' 
      } 
     }, 
     paths: { 
      jquery: 'vendor/jquery.min', 
      underscore: 'vendor/underscore.min', 
      react: 'vendor/react.min' 
     } 
    }); 
    </script> 

    <!-- 
    I put my spec files here 
    --> 
    <script type="text/javascript" src="spec/a-spec.js"></script> 
    <script type="text/javascript" src="spec/some-other-spec.js"></script> 
</head> 

<body> 
</body> 
</html> 

現在,這裏是一個例子spec文件:

describe("Circular List Operation", function() { 

    // The CircularList object needs to be loaded by RequireJs 
    // before we can use it. 
    var CircularList; 

    // require.js loads scripts asynchronously, so we can use 
    // Jasmine 2.0's async support. Basically it entails calling 
    // the done function once require js finishes loading our asset. 
    // 
    // Here I put the require in the beforeEach function to make sure the 
    // Circular list object is loaded each time. 
    beforeEach(function(done) { 
     require(['lib/util'], function(util) { 
      CircularList = util.CircularList; 
      done(); 
     }); 
    }); 

    it("should know if list is empty", function() { 
     var list = new CircularList(); 
     expect(list.isEmpty()).toBe(true); 
    }); 

    // We can also use the async feature on the it function 
    // to require assets for a specific test. 
    it("should know if list is not empty", function(done) { 
     require(['lib/entity'], function(entity) { 
      var list = new CircularList([new entity.Cat()]); 
      expect(list.isEmpty()).toBe(false); 
      done(); 
     }); 
    }); 
}); 

這裏是一個鏈接從茉莉花2.0文檔的異步支持部分:http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

+0

值得注意的是,這是我發現與[node-webkit](https://github.com/rogerwang/node-webkit)一起使用的唯一解決方案,與[RequireJS r.js插件](http:///requirejs.org/docs/1.0/docs/node.html),以便我可以測試導入AMD和Node.js模塊的代碼。 – jmort253 2014-05-07 19:59:02

+0

你的規格沒有使用amd,我認爲這是這個問題的全部目的。 – cancerbero 2016-02-03 01:10:56

3

Jasmine 2.0 standalone的另一個選擇是創建一個boot.js文件,並將其設置爲在所有AMD模塊加載後運行測試。

在我們的例子中編寫測試的理想最終用戶案例是不必一次性列出我們所有的spec文件或依賴項,並且只需要將* spec文件聲明爲具有依賴關係的AMD模塊。

例理想規格:規格/ JavaScript的/ sampleController_spec.js

require(['app/controllers/SampleController'], function(SampleController) { 
    describe('SampleController', function() { 
     it('should construct an instance of a SampleController', function() { 
     expect(new SampleController() instanceof SampleController).toBeTruthy(); 
     }); 
    }); 
}); 

理想的情況下加載的依賴和運行規範的背景行爲是完全不透明的人來上這個項目希望編寫測試,除了用AMD依賴創建一個* spec.js文件之外,他們不需要做任何事情。

爲了得到這一切的工作,我們創建了一個啓動文件和配置茉莉花使用它(http://jasmine.github.io/2.0/boot.html),並增加了一些魔法環繞需要暫時推遲運行測試,直到經過我們加載我們DEPS:

我們boot.js'‘執行’部分:

/** 
* ## Execution 
* 
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. 
*/ 

var currentWindowOnload = window.onload; 

// Stack of AMD spec definitions 
var specDefinitions = []; 

// Store a ref to the current require function 
window.oldRequire = require; 

// Shim in our Jasmine spec require helper, which will queue up all of the definitions to be loaded in later. 
require = function(deps, specCallback){ 
    //push any module defined using require([deps], callback) onto the specDefinitions stack. 
    specDefinitions.push({ 'deps' : deps, 'specCallback' : specCallback }); 
}; 

// 
window.onload = function() { 

    // Restore original require functionality 
    window.require = oldRequire; 
    // Keep a ref to Jasmine context for when we execute later 
    var context = this, 
     requireCalls = 0, // counter of (successful) require callbacks 
     specCount = specDefinitions.length; // # of AMD specs we're expecting to load 

    // func to execute the AMD callbacks for our test specs once requireJS has finished loading our deps 
    function execSpecDefinitions() { 
    //exec the callback of our AMD defined test spec, passing in the returned modules. 
    this.specCallback.apply(context, arguments);   
    requireCalls++; // inc our counter for successful AMD callbacks. 
    if(requireCalls === specCount){ 
     //do the normal Jamsine HTML reporter initialization 
     htmlReporter.initialize.call(context); 
     //execute our Jasmine Env, now that all of our dependencies are loaded and our specs are defined. 
     env.execute.call(context); 
    } 
    } 

    var specDefinition; 
    // iterate through all of our AMD specs and call require with our spec execution callback 
    for (var i = specDefinitions.length - 1; i >= 0; i--) { 
    require(specDefinitions[i].deps, execSpecDefinitions.bind(specDefinitions[i])); 
    } 

    //keep original onload in case we set one in the HTML 
    if (currentWindowOnload) { 
    currentWindowOnload(); 
    } 

}; 

我們基本上保持我們的AMD語法規範的堆棧,彈出他們,需要的模塊,執行與我們在它的斷言回調,然後運行茉莉花一旦一切都完成加載。

這個設置使我們可以等到我們單個測試所需的所有AMD模塊都加載完畢,並且不會通過創建全局變量來破壞AMD模式。實際上我們暫時覆蓋了需求,並且只使用require(我們的`src_dir:jasmine.yml爲空)加載我們的應用程序代碼,但這裏的總體目標是減少編寫規範的開銷。

+0

如果您使用Jasmine 2.0,很好的答案。像魅力一樣工作.. – mehrandvd 2015-12-18 21:33:43

3

您可以組合使用done與之前的過濾器來測試異步回調:

beforeEach(function(done) { 
    return require(['dist/sem-campaign'], function(campaign) { 
     module = campaign; 
     return done(); 
    }); 
    }); 
1

這是我要怎麼做才能運行使用所有我的消息來源和規格AMD/requirejs在HTML茉莉花規範。

這是加載茉莉,然後我的「單元測試啓動」我的index.html文件:

<html><head><title>unit test</title><head> 
<link rel="shortcut icon" type="image/png" href="/jasmine/lib/jasmine-2.1.3/jasmine_favicon.png"> 
<link rel="stylesheet" href="/jasmine/lib/jasmine-2.1.3/jasmine.css"> 
<script src="/jasmine/lib/jasmine-2.1.3/jasmine.js"></script> 
<script src="/jasmine/lib/jasmine-2.1.3/jasmine-html.js"></script> 
<script src="/jasmine/lib/jasmine-2.1.3/boot.js"></script> 
</head><body> 
<script data-main="javascript/UnitTestStarter.js" src="javascript/require.js"></script> 
</body></html> 

,然後我UnitTestStarter.js是這樣的:

require.config({ 
    "paths": { 
     .... 
}); 
require(['MySpec.js'], function() 
{ 
    jasmine.getEnv().execute(); 
})