在Jasmine单元测试中模拟AngularJS模块依赖性
我试图在将其他模块作为依赖项的模块中对单元测试控制器代码进行单元化,但是还无法弄清楚如何正确模拟它们.
I'm attempting to unit test controller code inside a module that takes other modules as dependencies, but haven't been able to figure out how to mock them properly.
我正在使用Jasmine Framework,并使用Karma(Testacular)运行测试.
I'm using the Jasmine Framework and running my tests with Karma (Testacular).
模块代码
var app = angular.module('events', ['af.widgets', 'angular-table']);
app.controller('eventsCtrl', function([dependencies]){
$scope.events = [];
...
});
规范代码
describe('events module', function(){
var $scope,
ctrl;
beforeEach(function(){
angular.mock.module('af.widgets', []);
angular.mock.module('angular-table', []);
module('events', ['af.widgets', 'angular-table']);
});
beforeEach(inject(function($rootScope, $controller){
$scope = $rootScope.new();
ctrl = $controller('NameCtrl', {
$scope: $scope,
});
}));
it('should have an empty events array', function(){
expect($scope.events).toBe([]);
})
});
我得到的错误是Karma是无模块af.widgets",因此显然我没有嘲笑模块依赖关系.有什么提示吗?
The error I'm getting is Karma is "no module af.widgets", so obviously I'm not mocking the module dependencies right. Any hints?
如果要模拟一个声明一个或多个服务的模块,我将使用以下代码:
If you want to mock a module that declare one or more services I have used this code:
beforeEach(function(){
module('moduleToMock');
module(function ($provide) {
$provide.value('yourService', serviceMock);
});
});
如果要模拟的服务也是要进行单元测试的服务(用另一个茉莉花描述),这将很有用.
fscof提出的解决方案很好,但是您不能为angular-table
模块创建单元测试.
This is useful if the service you want to mock is also a service that you want to unit test (in another jasmine describe).
The solution proposed by fscof is fine but you cannot create a unit test for the angular-table
module.