Gre*_*eir 13 javascript unit-testing dependency-injection jasmine angularjs
假设我有一个服务依赖于$ rootScope中的值,就像下面的(普通)服务一样:
angular.module('myServices', [])
.factory('rootValGetterService', function($rootScope) {
return {
getVal: function () {
return $rootScope.specialValue;
}
};
});
Run Code Online (Sandbox Code Playgroud)
如果我想通过在$ rootScope中添加一个值进行单元测试,那么最好的方法是什么?
Mar*_*zee 21
...
var $rootScope;
beforeEach(inject(function(_$rootScope_) {
$rootScope = _$rootScope_;
}));
...
Run Code Online (Sandbox Code Playgroud)
通过使用provide(),您可以注入一个新的$ rootScope:
describe('in rootValGetter', inject(function ($rootScope) {
var scope;
var testRootValGetter;
beforeEach(function () {
scope = $rootScope.$new();
module(function ($provide) {
$provide.value('$rootScope', scope);
});
inject(function ($injector) {
testRootValGetterService = $injector.get('rootValGetterService');
});
});
it('getVal returns the value from $rootScope', function() {
var value = 12345;
scope.specialValue = value;
expect(testRootValGetterService.getVal()).toBe(value);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19830 次 |
| 最近记录: |