因果报应错误:未知提供者
Karma error: unknown provider
我们正在尝试用Karma测试我们的控制器,但Karma一直抱怨未知的提供者:
错误:
[$injector:unpr]
Unknown provider:userProvider
<-user
我们注入user
正确吗?
controller-test.js:
describe('Controller', function () {
beforeEach(module('myApp'));
var ctrl, scope, user;
beforeEach(inject(function ($controller, $rootScope, _user_) {
scope = $rootScope.$new();
ctrl = $controller('controller', {
$scope: scope
});
user = _user_;
}));
it("should have scope defined", function () {
expect(scope).toBeDefined();
});
});
app.js:
(function () {
var myApplication = angular.module("myApp", [
"angucomplete-alt"
]);
fetchData().then(bootstrapApplication);
function fetchData() {
var initInjector = angular.injector(["ng"]);
var $http = initInjector.get("$http");
// Get user info before app is loaded
return $http.get('/api/user').then(function (response) {
myApplication.value("user", response.data);
}, function (errorResponse) {
// Handle error case
console.error("Obtaining user information failed when bootstrapping Angular app");
});
}
function bootstrapApplication() {
angular.element(document).ready(function () {
angular.bootstrap(document, ["myApp"]);
});
}
})();
controller.js:
angular.module("myApp")
.controller("controller", ["$scope", "user", "$window",
function ($scope, user, $window) { ... }]);
在测试控制器时,应该单独进行测试。我将简单地将模拟的user
对象放入locals哈希映射中(与$scope
一起),例如
describe('Controller', function() {
var ctrl, scope, user, $window;
beforeEach(function() {
user = {
id: 'fake_id',
username: 'fake_username'
};
$window = jasmine.createSpyObj('$window', ['some', 'methods']);
module('myApp');
inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('controller', {
$scope: scope,
user: user,
$window: $window
});
});
});
});
一个示例规范可能是测试注入的user
对象是否被放置到作用域中。如
it('puts the user onto the controller scope', function() {
expect(scope.user).toBe(user);
});
在使用ngMock
的单元测试中(我假设您有),所有$http
调用都经过一个模拟后端($httpBackend
),该后端不执行真正的HTTP调用,除非特别配置为这样做。
即使您的fetchData
函数在测试时运行(我怀疑它没有这样做,否则您会得到一些控制台错误),它也不会检索任何数据。
相关文章:
- 对广告服务器的未知信标调用
- Axios spread()具有未知数量的回调参数
- 反汇编的javascript jit代码调用未知函数
- 未知”<#"构造
- Safari 5.1.7下载文件名未知的csv文件
- 带有 JavaScript 随机数函数的未知问题
- 哪个原型用于创建具有未知标记的节点
- xmlHttp.responseText未知错误定义
- JavaScript删除未知侦听器
- 因果报应测试中的未知提供者
- 有角度的“;未知提供者”;在约曼应用程序中使用Grunt Build缩小后出错
- 错误:$injector:unp未知提供者:未知提供者:bProvider<-b
- Angular uibModal,Resolve,未知提供者
- Angularjs - 未知的提供者:
- 当添加一个服务和一个过滤器或多个服务时,我在做什么导致未知提供者
- 永远运行sail.js+angularjs项目得到未知提供者:a
- 又一个'未知提供者'用于AngularJS服务
- AngularJS未知提供者
- 尽管其他控制器和服务工作,未知的提供者错误
- 因果报应错误:未知提供者