我已经阅读了许多关于将控制器注入茉莉花单元测试的示例,但我不断收到“错误:[ng:areq] http://errors.angularjs.org/undefined/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined”。
这是我的代码:
main.spec.js:
'use strict'
describe("Testing Main Controller", function(){
var scope, controller;
var dummyFunction = function(){};
var defaultDocument = {
_id: "123456"
};
beforeEach(module('app.controllers'));
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('MainCtrl', {
$scope: scope,
SearchService: dummyFunction,
ResultsService: dummyFunction,
FacetService: dummyFunction,
EsDateService: dummyFunction,
Likes: dummyFunction,
Bookmarks: dummyFunction
});
}));
describe("Likes", function(){
it('shall give the user the ability to like a document that is currently being displayed.', function(){
scope.updateLike([defaultDocument]);
expect(defaultDocument.isLiked).toBe(true);
});
it('shall give the user the ability to remove a like from a document that is currently being displayed.', function(){
defaultDocument.isLiked = true;
scope.updateLike([defaultDocument]);
expect(defaultDocument.isLiked).toBe(true);
});
});
});
main_controller.js:
'use strict';
angular.module('app.controllers')
.controller('MainCtrl', function($scope, SearchService, ResultsService, FacetService, EsDateService, Likes, Bookmarks) {
});
app.js:
angular.module('app.services', ['ngResource', 'elasticjs.service']);
angular.module('app.controllers', [ 'app.services']);
var app = angular.module('app', [
'ui.bootstrap',
'elasticjs.service',
'app.services',
'app.controllers',
'app.config',
'facet.directives',
'ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
controller: 'SearchCtrl',
templateUrl: 'views/search/search.html'
})
.when('/journal', {
controller: 'JournalCtrl',
templateUrl: 'views/journal/journal.html'
})
.otherwise({
redirectTo: '/'
});
}
]);
app.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix("!");
}
]);
当我将MainCtrl附加到app而不是app.controllers时,它似乎找到了MainCtrl。我究竟做错了什么?
答案 0 :(得分:1)
您不需要为app模块重新声明依赖项,因为app模块会注入app.controllers
beforeEach(module('app'));
快速举例说明如何解决问题 - http://jsfiddle.net/PtXFb/