问题描述
我试图单元测试控制器code,它需要其它模块依赖一个模块内,但一直没能搞清楚如何正确地嘲笑他们。
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.
我使用的是茉莉花框架和噶(Testacular)上运行我的测试。
I'm using the Jasmine Framework and running my tests with Karma (Testacular).
模块code
var app = angular.module('events', ['af.widgets', 'angular-table']);
app.controller('eventsCtrl', function([dependencies]){
$scope.events = [];
...
});
规格code
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([]);
})
});
我得到的错误是噶是没有模块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?
推荐答案
如果你想嘲笑那些声明一个或多个服务我已经使用这个code模块:
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提出的解决方案是好的,但你不能创建的角表
模块单元测试。
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.
这篇关于在茉莉花单元测试嘲讽角模块依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!