我正在使用 Jasmine 测试一些 Angular.js 代码。为此,我需要一个 Angular 注入(inject)器:
var injector = angular.injector(['ng', 'ngRoute', 'mainModule']);
这工作正常,但是当我开始测试使用 $location 的 Controller 时,我必须将它添加到注入(inject)器中:
var injector = angular.injector(['ng', 'ngRoute', 'location', 'mainModule']);
现在这会抛出一个错误:
Error: Error: [$injector:modulerr] Failed to instantiate module location due to:
Error: [$injector:nomod] Module 'location' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
如何在其中包含 $location 服务?谢谢。
------------编辑----------------
由于答案不多,我想我会添加一些细节。
这是我正在尝试测试的 Controller (或者它的定义,我不会粘贴所有代码):
var app = angular.module('mainModule');
app.controller('appController', ['$window', '$scope', '$location', '$wsService', '$userService', '$labelService', function ($window, $scope, $location, $wsService, $userService, $labelService) {
//body of the controller
}]);
您已经在原帖中看到我如何在单元测试中创建注入(inject)器,下面是我如何使用注入(inject)器创建 Controller :
var scope;
var controller;
var getController = function() {
injector.invoke( ['$rootScope', '$controller', function ($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('appController', {$scope: scope});
}]);
};
希望这将有助于产生一些潜在的答案。谢谢
回答我自己的问题。以下是如何测试以下 Controller :
var app = angular.module('mainModule');
app.controller('appController', ['$window', '$scope', '$location', '$userService', function ($window, $scope, $location, $userService) {
//body of the controller
}]);
1 在单元测试中创建注入(inject)器:
var injector = angular.injector(['ng', 'ngRoute', 'mainModule']);
2 调用所需的服务:
injector.invoke( ['$userService', function ($userService) {
service = $userService;
}]);
3模拟位置服务:
var mockLocation = {
path : ""
};
我只需要我正在测试的 Controller 的 path
,因此我没有模拟其他任何东西,而是模拟您需要的任何其他东西。
4调用 Controller :
var scope;
var controller;
var getController = function() {
injector.invoke( ['$rootScope', '$controller', function ($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('appController', {$scope: scope, $location: mockLocation});
}]);
};
现在 Controller 可以用于单元测试了。
这确实消除了“未知提供商”和其他与定位服务相关的错误。
This博文帮我找到了答案,感谢作者。
Tôi là một lập trình viên xuất sắc, rất giỏi!