使用Jasmine和Karma对AngularJS页面程序进行测试(2)

从代码中你可以看到我们注入了我们自己的 scope,因此我们可以在它的外部验证它的信息。同时,别忘了模拟模块本身(第7行代码)!我们现在已经为测试做好了准备:

home.tests.js

// 测试从这里开始 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'}]);

我们的测试: home.tests.js

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

都放到一起

home.tests.js

'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'); }); });

技巧

Karma会运行所有文件中的所有测试用例,如果你只想运行所有测试的一个子集,修改 describe 或 it 为 ddescribe 或 iit 来运行个别的一些测试。如果有些测试你不想运行他们,那么修改 describe 或 it 为 xdescribe 或 xit 来忽略这些代码。

你也可以在html文件的页面上运行你的测试。举例的代码如下:
home.runner.html

<!DOCTYPE html> <html> <head> <title>Partner Settings Test Suite</title> <!-- include your script files (notice that the jasmine source files have been added to the project) --> <script type="text/javascript" src="https://www.jb51.net/jasmine/jasmine-1.3.1/jasmine.js"></script> <script type="text/javascript" src="https://www.jb51.net/jasmine/jasmine-1.3.1/jasmine-html.js"></script> <script type="text/javascript" src="https://www.jb51.net/angular-mocks.js"></script> <script type="text/javascript" src="https://www.jb51.net/home.tests.js"></script> <link href="https://www.jb51.net/jasmine/jasmine-1.3.1/jasmine.css"/> </head> <body> <!-- use Jasmine to run and display test results --> <script type="text/javascript"> var jasmineEnv = jasmine.getEnv(); jasmineEnv.addReporter(new jasmine.HtmlReporter()); jasmineEnv.execute(); </script> </body> </html>

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgyxzs.html