2013-04-25 50 views
25

我玩用qunithttp://qunitjs.com測試運行(http://karma-runner.github.io/0.8/index.html)。我成功創建並運行了簡單的測試(100%JavaScript),但現在我試圖使用HTML Fixtures來測試與DOM節點交互的代碼。我可以通過「文件」,宣佈他們加載這些裝置以這樣的方式如何使用使用Qunit的Karma測試運行器使用HTML設備?

{pattern: 'fixtures/myfixture.html', watched: true, served: true, included: false} 

它得到由因果報應的服務器提供的,但我不明白,我怎麼能訪問到它的DOM :(

讓我們假設我的燈具是一個包含以下標記一個簡單的HTML文件:

<div id="container">hello world</div> 

我如何寫一個測試,可以訪問到該節點(DIV) 的「文件」是關係到「 context.html「文件下的」靜態「文件夾,據我所知...所以HTM在哪裏L我的夾具?

+0

檢查我的答案在這裏:http://stackoverflow.com/questions/15214760/unit-testing- angularjs-directive-with-templateurl/16528985#16528985 – 2013-05-13 19:04:42

回答

23

我沒有使用AngularJS ...我通過採用jasmine-jquery解決了問題:https://github.com/velesin/jasmine-jquery(我只使用jasmine作爲燈具,我的測試仍然使用qunit編寫)。 在我的配置文件,我有以下幾點:

frameworks = ['qunit', 'jasmine']; 

    files = [ 

     JASMINE, 
     JASMINE_ADAPTER, 
     QUNIT, 
     QUNIT_ADAPTER, 

     // dependencies 
     {pattern: 'src/main/webapp/js/libs/jquery/jquery-1.8.3.js', watched: false, served: true, included: true}, 
     {pattern: 'src/test/js/lib/jasmine-jquery.js', watched: false, served: true, included: true}, 

     // fixtures 
     {pattern: 'src/test/js/**/*.html', watched: true, served: true, included: false}, 
     {pattern: 'src/test/js/**/*.json', watched: true, served: true, included: false}, 
     {pattern: 'src/test/js/**/*.xml', watched: true, served: true, included: false}, 

     // files to test 
     {pattern: 'src/test/js/**/*.js', watched: true, served: true, included: true} 
    ]; 

然後在我的測試文件:

module("TestSuiteName", { 
    setup: function() { 
     var f = jasmine.getFixtures(); 
     f.fixturesPath = 'base'; 
     f.load('src/test/js/TestFixture.html'); 
    }, 
    teardown: function() { 
     var f = jasmine.getFixtures(); 
     f.cleanUp(); 
     f.clearCache(); 
    } 
}); 
+0

幹得好哥們。你還需要在配置中使用JASMINE和JASMINE_ADAPTER嗎? – NickL 2013-07-25 19:39:00

+8

爲了使它適用於我,我不得不添加「預處理器:{'**/*。html':[]}」。這將刪除默認情況下在Karma 0中使用的html2js預處理器。10 – 2013-08-11 11:33:07

+0

[相關的github問題討論關於Karma中的預處理器](https://github.com/karma-runner/karma/issues/788)。 – jfroom 2013-10-22 16:35:37

8

如果您使用AngularJS,則可以使用html2js預處理器。 如何做到這一點的一個例子是在https://github.com/vojtajina/ng-directive-testing

這些html文件由Karma提供,但它們不包含在頁面中,因此您必須通過xhr請求獲取它們。

這裏是一個類似的預處理,即HTML文件轉換成JS字符串(不緊角):https://github.com/karma-runner/karma-html2js-preprocessor你可以看到如何在端到端測試中使用它:https://github.com/karma-runner/karma-html2js-preprocessor/tree/master/e2e-test

注:本html2js預處理器不是Karma 0.8的一部分,只能使用Karma 0.9+(目前在Canary頻道),所以你必須使用金絲雀(它包含很多變化; - ))...

+0

我也非常有興趣測試與業力的DOM。這將在未來的版本中提供嗎?還是應該尋求解決方法?我可能不會使用Angular ... – zigomir 2013-05-01 23:40:25

+0

只需使用canarma釋放業力(它最終會變得穩定;-)並使用karma-html2js預處理器插件,這對於AngularJS來說並不嚴密。 – Vojta 2013-05-12 03:05:11

+1

如何在npm上安裝金絲雀版本?對不起,這個愚蠢的問題。 – 2013-06-21 00:44:23

相關問題