【问题标题】:AngularJS - Unit testing service with value dependency injectionAngularJS - 具有值依赖注入的单元测试服务
【发布时间】:2013-04-11 21:35:00
【问题描述】:

我目前正在尝试使用 AngularJS。我创建了一个简单的服务,它是从一些遥远的数据初始化的。 url 作为应用程序值传递。

//App declaration
angular.module('myApp', ['myApp.services']).value('someUrl', 'http://www.example.com');

//Service declaration
angular.module('myApp.services', ['someUrl']).factory('MyService', function(someUrl) {
    var data;
    "Do stuff"  
    return data;
});

现在,我正在尝试对此进行单元测试,但我无法正确设置“someUrl”参数。我已经尝试过这样的事情,但没有成功:

angular.module('myApp', ['myApp.services']).value('someUrl', 'test/test.json');

describe('Services', function() {
    beforeEach(module('myApp.services'));

    describe('MyService', function() {
        it('should return {success: true}', inject(function() {
            expect(data).toEqual({success: true});
        }));
    });
});

但是,我总是收到“无模块:someUrl”错误。在单元测试期间初始化应用程序值的正确语法是什么?

【问题讨论】:

    标签: unit-testing angularjs angularjs-service


    【解决方案1】:

    您将值设置为“myApp”模块并正在测试“myApp.services”模块。您应该将module('myApp.services') 更改为module('myApp')

    无论如何,有更好的方法来做到这一点。您可以使用模拟 module 来注入 $provide,这样您就可以覆盖任何依赖项。

    这就是你的规范的样子:

    describe('Services', function() {
      // here we load the module myApp and load an additional one that
      // allows you to override your dependency
      beforeEach(module('myApp', function($provide) {
        $provide.value('someUrl', 'test/test.json');
      }));
    
      describe('MyService', function() {
        it('should return {success: true}', inject(function() {
            expect(data).toEqual({success: true});
        }));
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多