'use strict';
describe('MainCtrl', function(){
var scope;//我们会在测试中使用这个scope
//模拟我们的Application模块并注入我们自己的依赖
beforeEach(angular.mock.module('Application'));
//模拟Controller,并且包含 $rootScope 和 $controller
beforeEach(angular.mock.inject(function($rootScope, $controller){
//创建一个空的 scope
scope = $rootScope.$new();
//声明 Controller并且注入已创建的空的 scope
$controller('MainCtrl', {$scope: scope});
});
// 测试从这里开始
});
  从代码中你可以看到我们注入了我们自己的 scope,因此我们可以在它的外部验证它的信息。同时,别忘了模拟模块本身(第7行代码)!我们现在已经为测试做好了准备:
// 测试从这里开始
it('should have variable text = "Hello World!"', function(){
expect(scope.text).toBe('Hello World!);
});

  如果你运行这个测试,它可以在任何指向Karma的浏览器中执行,并且测试通过。
  发送$resource请求
  现在我们已经准备好测试 $resource 请求。要完成这个请求,我们需要使用到 $httpBackend, 它一个模拟版本的Angular $http。我们会创建另一个叫做 $httpBackend 的变量,在第二个 beforEach块中,注入 _$httpBackend_ 并将新创建的变量指向 _$httpBackend_。接下来我们会告诉 $httpBackend 如何对请求做出响应。

 

$httpBackend = _$httpBackend_;
$httpBackend.when('GET', 'Users/users.json').respond([{id: 1, name: 'Bob'}, {id:2, name: 'Jane'}]);

  我们的测试:

 

it('should fetch list of users', function(){
$httpBackend.flush();
expect(scope.users.length).toBe(2);
expect(scope.users[0].name).toBe('Bob');
});

  都放到一起

 

'use strict';
describe('MainCtrl', function(){
var scope, $httpBackend;//we'll use these in our tests
//mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('Application'));
//mock the controller for the same reason and include $rootScope and $controller
beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_){
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', 'Users/users.json').respond([{id: 1, name: 'Bob'},
{id:2, name: 'Jane'}]);
//create an empty scope
scope = $rootScope.$new();
//declare the controller and inject our empty scope
$controller('MainCtrl', {$scope: scope});
});
// tests start here
it('should have variable text = "Hello World!"', function(){
expect(scope.text).toBe('Hello World!');
});
it('should fetch list of users', function(){
$httpBackend.flush();
expect(scope.users.length).toBe(2);
expect(scope.users[0].name).toBe('Bob');
});
});