【问题标题】:How can I run common code in tests using Karma + Jasmine + AngularJS?如何使用 Karma + Jasmine + AngularJS 在测试中运行通用代码?
【发布时间】:2015-01-06 18:56:12
【问题描述】:

我正在使用 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', '');
  });

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

谢谢大家。

【问题讨论】:

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


    【解决方案1】:

    你应该看看 ng-html2js-preprocessor:

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

    它会将你所有的模板打包成一个模板缓存模块(在后台使用$templateCache),你可以使用:

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

    【讨论】:

    • 谢谢,会的。我现在要走了,但明天早上我会尝试一下,然后我会发布结果。
    • 我想错了。这个插件把所有的模板都放在了$templateCache中,所以我不需要一直添加。谢谢!
    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2014-05-04
    • 2013-09-29
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多