AngularJS +测试锚元素单击

时间:2014-01-14 15:05:12

标签: angularjs jasmine

我是AngularJS的新手。我正在用Jasmine创建一些单元测试。我试图了解如何测试链接是否被点击。例如,我写了以下内容:

it('should click the link', inject(function ($compile, $rootScope) {
  var element = $compile('<a href="http://www.google.com" >Google.com</a>')($rootScope);
  $rootScope.$digest();

  expect(true).toBeTruthy();
}));

请注意,我不想测试浏览器窗口是否被重定向到Google。有时候我的链接会将用户重定向到网址。有时他们会触发一些JavaScript。无论哪种方式,我都试图测试链接是否被点击。最后,我将添加一些行为,以确保跳过链接的默认行为。考虑到测试驱动开发的想法,我需要进行测试以确保当前正在检测链接点击。

如何使用Jasmine在AngularJS中测试?

谢谢

1 个答案:

答案 0 :(得分:2)

这不是AngularJS单元/集成测试。这更像是一次端到端测试。 如果你想把它写成&#34; Angular Way&#34;你可以这样写:

在视图中:

<p ng-click='redirectToGoogle()'>Google.com</p>

在控制器中:

$scope.redirectToGoogle = function(){
  $location.path('http://www.google.com');
};

在你的测试中:

describe('Redirect', function(){

  var location, scope, rootScope, controller;

  beforeEach(function(){
    inject(function ($injector){
      rootScope = $injector.get('$rootScope');
      scope = rootScope.$new();

      controller = $injector.get('$controller')("nameOfYourController", {$scope: scope});

      location = $injector.get('$location');
    });
  });

  it('should redirect to google', function){
    spyOn(location, 'path');

    scope.redirectToGoogle();

    expect(location.path).toHaveBeenCalledWith('http://www.google.com');
  });

});
相关问题