AngularJS - 具有值依赖注入的单元测试服务

Cei*_*hir 4 unit-testing angularjs angularjs-service

我目前正在试验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;
});
Run Code Online (Sandbox Code Playgroud)

现在,我正在尝试对此进行单元测试,但我无法正确设置"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});
        }));
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,我总是收到"No module:someUrl"错误.在单元测试期间初始化app值的正确语法是什么?

Cai*_*nha 6

您将值设置为"myApp"模块并正在测试"myApp.services"模块.你应该module('myApp.services')改为module('myApp').

无论如何,有一个更好的方法.你可以使用mock 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});
    }));
  });
});
Run Code Online (Sandbox Code Playgroud)