我的test_Spec.js
describe('Myctrl', function() {
var $httpBackend, scope, createController, authRequestHandler;
// Set up the module
beforeEach(module('myApp'));
beforeEach(inject(function($injector) {
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
authRequestHandler = $httpBackend.when('GET', 'http://www.w3schools.com/angular/customers.php')
.respond(true);
// Get hold of a scope (i.e. the root scope)
$rootScope = $injector.get('$rootScope');
// The $controller service is used to create instances of controllers
var $controller = $injector.get('$controller');
createController = function() {
return $controller('Myctrl', {'$scope' : scope});
};
})
);
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('http://www.w3schools.com/angular/customers.php');
var controller = createController();
expect(scope.names).toBe(true);
$httpBackend.flush();
});
});
这是我的test.js
服务电话
var myApp = angular.module('myApp', []);
app.controller('Myctrl', function($Scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$Scope.names = response.records;});
});
和these是我得到的错误:
以下是错误摘要:
Error: [$injector:unpr] Unknown provider: $rootScopeProvider <- $rootScope <- $httpBackend http://errors.angularjs.org/1.2.0/$injector/unpr?p0=%24rootScopeProvider%20%3C-%20%24rootScope%20%3C-%20%24httpBackend
TypeError: Cannot read property 'expectGET' of undefined
TypeError: Cannot read property 'verifyNoOutstandingExpectation' of undefined
错误的解决方案是什么?我尝试了几件事,但我无法弄清楚确切的解决方案。请协助。
答案 0 :(得分:1)
您希望将依赖项中的拼写错误注入控制器。
将$Scope
更改为$scope
;)
至于测试中的错误,请尝试以这种方式注入服务:
beforeEach(inject(function (_$httpBackend_, _$rootScope_, _$controller_) {
…
答案 1 :(得分:1)
Well, I know it is too late to answer but in case anyone else stumbles upon similar error, you can try the following:
You never defined the scope
variable. You just declared it. So it actually should be:
scope = $injector.get('$rootScope').$new();
Also note the $new()
. For every new test case, (as a best practice) you should get a new scope.