如何在PhantomJS测试中单击A指令 [英] How to ng-click an A directive in a PhantomJS test

查看:80
本文介绍了如何在PhantomJS测试中单击A指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由Yeoman用角度生成器生成的应用程序。

App generated by Yeoman with angular-generator.

指令:

angular.module('psApp').directive('scrollTop', function () {
  return {
    restrict: 'A',
    scope: true,
    template: '<a href="#" ng-click="click()" class="scroll-top"><span class="glyphicon glyphicon-arrow-up"></span> Back to top</a>',
    controller: ['$scope', '$element', '$document', function ($scope, $element, $document) {
      $scope.click = function () {
        $document.scrollTop(0, 500);
      };
    }]
  };
});

测试:

describe('Directive: scrollTop', function () {

  // load the directive's module
  beforeEach(module('psApp'));

  var scope, element;

  beforeEach(inject(function ($rootScope, $compile) {
    scope = $rootScope.$new();
    element = $compile('<div scroll-top></div>')(scope);
    scope.$apply();
  }));

  it('should have "Back to top" as text', inject(function () {
    expect(element.html()).toBe('<a href="#" ng-click="click()" class="scroll-top"><span class="glyphicon glyphicon-arrow-up"></span> Back to top</a>');
    expect(element.text()).toBe(' Back to top');
    element.click();
  }));
});

错误:


PhantomJS 1.9.7(Mac OS X)指令:scrollTop应该有返回顶部作为文本
TypeError:'undefined'不是函数(评估'element.click()')

PhantomJS 1.9.7 (Mac OS X) Directive: scrollTop should have "Back to top" as text TypeError: 'undefined' is not a function (evaluating 'element.click()')

我无法理解问题所在。 :(请发布功能代码。

I cannot understand where the problem is. :( Please post functional code.

推荐答案

由于某些原因,PhantomJS中没有click()函数。这是解决方法:

For some reason PhantomJS does not have a click() function in it. Here is the workaround:

//Need to create a cross browser click() function no .click() in PhantomJS
function click(el){
    var ev = document.createEvent('MouseEvent');
    ev.initMouseEvent(
        'click',
        true /* bubble */, true /* cancelable */,
        window, null,
        0, 0, 0, 0, /* coordinates */
        false, false, false, false, /* modifier keys */
        0 /*left*/, null
    );
    el.dispatchEvent(ev);
}

以下是如何使用它:

it('Should set the month when the month is changed', function(){
    var obj = element[0].getElementsByClassName('month_opt')[1];
    click(obj);
    expect(scope.dt.getMonth()).toEqual(1);
});

这篇关于如何在PhantomJS测试中单击A指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆