如何使用Karma + Jasmine + AngularJS在测试中运行公共代码?

时间:2015-01-06 18:56:13

标签: angularjs unit-testing jasmine karma-runner karma-jasmine

我使用Karma对AngularJS应用程序运行单元测试。问题是我使用ui-router插件,并且它使一些XHR请求运行模板迫使我模拟这些请求。因此,我认为自己会为每个测试文件重复此操作:

  beforeEach(function($templateCache) {
    $templateCache.put('templates/layout.html', '');
    $templateCache.put('templates/dashboard/index.html', '');
    $templateCache.put('templates/session/login.html', '');
  });

如何为我的所有单元测试运行这段代码?我试过谷歌搜索,但没有运气。另外,我应该以其他方式这样做吗?请分享您的意见。

谢谢大家。

1 个答案:

答案 0 :(得分:3)

您应该查看ng-html2js-preprocessor:

https://github.com/karma-runner/karma-ng-html2js-preprocessor

它会将您的所有模板批量处理为模板缓存模块(使用引擎盖下的$templateCache):

describe('SOMETHING', function() {
    beforeEach(module('templates'));