2013-04-25 66 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

相关问题