如何使用Qunit的Karma测试运行器使用HTML装置?

dav*_*ode 25 javascript tdd unit-testing qunit karma-runner

我正在使用qunit(http://qunitjs.com)与Karma测试运行器(http://karma-runner.github.io/0.8/index.html)一起玩.我成功创建并运行了简单的测试(100%JavaScript),但现在我正在尝试使用HTML fixture来测试与DOM节点交互的代码.我可以通过这种方式在"文件"中声明它们来加载这些灯具:

{pattern: 'fixtures/myfixture.html', watched: true, served: true, included: false}
Run Code Online (Sandbox Code Playgroud)

它得到了karma的服务器,但我不明白我怎么能访问它的DOM :(

假设我的fixture是一个包含以下标记的简单html文件:

<div id="container">hello world</div>
Run Code Online (Sandbox Code Playgroud)

如何编写可以访问该节点(div)的测试?据我所知,"文档"与"静态"文件夹下的"context.html"文件有关...那么我的夹具的HTML在哪里?

dav*_*ode 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}
    ];
Run Code Online (Sandbox Code Playgroud)

然后在我的测试文件中:

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();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 为了使它适用于我,我必须添加"预处理器:{'**/*.html':[]}".这将删除默认为我在Karma 0.10中打开的html2js预处理器 (8认同)

Voj*_*jta 8

如果您使用的是AngularJS,则可以使用html2js预处理器. 如何做到这一点的一个例子是https://github.com/vojtajina/ng-directive-testing.

这些html文件由Karma提供,但它们不包含在页面中,因此您必须获取它们 - 可能是通过xhr请求.

这是一个类似的预处理器,它将html文件转换为JS字符串(不是Angular):https://github.com/karma-runner/karma-html2js-preprocessor您可以在e2e测试中看到如何使用它:https://github.com/karma-runner/karma-html2js-preprocessor/tree/master/e2e-test

注意:这个html2js预处理器不是Karma 0.8的一部分,插件只适用于Karma 0.9+(目前在canary频道),所以你必须使用canary(包含很多变化; - ))...