相关疑难解决方法(0)

如何在AngularJS指令测试中模拟单击事件?

我已经尝试按照ng-directive-testing repo 的格式来编写我编写的指令.当用户点击元素时,该指令基本上呈现叠加.这是指令(简化):

mod.directive('uiCopyLinkDialog', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var $elm = angular.element(element);
            element.bind('click', function(event) {
                $elm.addClass('test');
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

我写的测试看起来像这样:

describe('pre-compiled link', function () {

    beforeEach(mocks.inject(function($compile, $rootScope) {
        scope = $rootScope;
        element = angular.element('<span class="foo" ui-copy-link-dialog="url"></span>');
        $compile(element)(scope);
        scope.$digest();
    }));

    it("should change the class when clicked", function () {
        element.click(); // this returns "'undefined' is not a function"
        element[0].click(); // so does this
        $(elm).click(); // this uses jquery and doesn't *seem* to fail …
Run Code Online (Sandbox Code Playgroud)

phantomjs angularjs angularjs-directive

48
推荐指数
2
解决办法
5万
查看次数

测试JavaScript单击使用Sinon的事件

我正在尝试生成一些测试,以便能够更好地理解如何使用Mocha,Chai,Sinon和jQuery的组合来测试DOM事件.我想检查单击div元素时是否正确触发了警报功能.我知道HTML元素的设置是正确的jQuery,但我不完全确定如何为下面的代码生成传递测试.特别奇怪的是,我在浏览器中打开HTML文件时出现对话,所以我知道'$('#thingy')行.触发器('click')'正在做我期望的事情.我目前得到以下内容,'TypeError:对象不是函数'

我的测试文件的相关部分,tests.js

describe('DOM tests - div element', function() {
$("body").append("<div id='thingy'>hello world</div>")
$('#thingy').attr('class', 'thingy');
$('#thingy').click(function() { alert( "I've been clicked!" ); });


it('should have called alert function', function () {
  var spy = sinon.spy(alert);
  $('#thingy').trigger('click')
  sinon.assert(spy.called);
});
Run Code Online (Sandbox Code Playgroud)

我的HTML文件非常标准,index.html

<!doctype html>
<html>
<head>
    <title>Tests</title>
    <link rel="stylesheet" href="mocha.css" />
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
    <div id="mocha"></div>
    <script src="mocha.js"></script>
    <script src="chai.js"></script>
    <script src="sinon-1.10.2.js"></script>
    <script>
        mocha.ui('bdd');
        mocha.reporter('html');
        var expect = chai.expect;
    </script>
    <script src="tests.js"></script>
    <script>
        mocha.run();
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

javascript bdd mocha.js sinon chai

8
推荐指数
1
解决办法
1万
查看次数