【问题标题】:Angular unit test for a service with constants using Jasmine使用 Jasmine 对具有常量的服务进行 Angular 单元测试
【发布时间】:2015-11-16 09:50:47
【问题描述】:

我有以下带有常量的服务:

angular.module('app',[]).constant('alertType',{
  success:1,
  error:0  
})
.factory("dataService",dataService);

dataService.$inject = ['$timeout', 'alertType']

function dataService($timeout, alertType) {
    return {
        //some code related to the service
    } 
}

这是服务检查是否注册的测试用例

describe('Testing "dataService" service', function() {
  var _dataService;

  beforeEach(function() {
    module('app');

    inject(function(dataService) {
      _dataService = dataService;
    });
  });
  it('Should be registered', function() {
    expect(_dataService).toBeDefined();
  });
});

由于某种原因它不起作用。我收到一个很长的错误,看起来像这样:

错误:[$injector:unpr] 未知提供者:dataServiceProvider http://errors.angularjs.org/1.3.0/$injector/unpr?p0=dataServiceProvider%20%3C-%20dataService

我做得对还是有什么问题?

【问题讨论】:

  • 请定义“它不起作用”
  • @Phil 添加了我收到的错误描述
  • 确保在您的 karma 文件中包含引导应用程序 ui-bootstrap 所需的所有文件
  • 您似乎没有将源文件包含到 Karma 配置文件中。在源文件中放一个console.log,检查是否包含
  • @BiJ 你看到console.log 在你运行测试套件后放入源文件的输出了吗?

标签: angularjs jasmine karma-runner karma-jasmine


【解决方案1】:

尝试在描述块的顶部模拟您的提供程序,如下所示:

beforeEach(module($provide => {
 $provide.constant('alertType',{
      success: 1,
      error: 0
   });
}));

更多详情请参考这个答案:Unknown Provider when unit testing filter

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 2020-03-14
    相关资源
    最近更新 更多