Jasmine点击触发器不适用于<a>

时间:2016-04-18 10:43:47

标签: javascript jasmine jasmine-jquery

Here's the spec I am running

describe("Test", function() {

    beforeEach(function(){
        loadFixtures('modal.html');
    });

    it ("click a tag", function(){

        var spy = spyOnEvent($('.modal-link'), 'click');
        $('.modal-link').trigger('click');
        expect('click').toHaveBeenTriggeredOn($('.modal-link'));
        expect(spy).toHaveBeenTriggered();

    });

});

Inside the fixture (modal.html), it looks like this

<a class="modal-link">Test Link</a>

The test fails with this error:

Expected event [object Object] to have been triggered on [object Object]at Object.<anonymous>

Expected event click to have been triggered on [object Object] at Object.<anonymous>

But when I replace the a tag with div, span or p, the test passes.

<div class="modal-link">Test Link</div>

Is there some reason the a tag is not clickable in my test?

Edit on 19/04: I use Karma to run the test, here's the config file

module.exports = function(config) {
  config.set({
    frameworks: ['jquery-1.11.0', 'jasmine-jquery', 'jasmine'],
    reporters: ['mocha'],
    browsers: ['PhantomJS'],
    plugins: [
      // Karma will require() these plugins
      'karma-jasmine',
      'karma-jasmine-jquery',
      'karma-jquery',
      'karma-phantomjs-launcher',
      'karma-mocha-reporter'
    ],
    preprocessors: {
      'test/spec/**/*.html': ['html2js']
    },
    autoWatch: true,
    files: [
      {pattern: 'app/libs/jquery.min.js', watched: true, included: true, served: true},
      {pattern: 'app/libs/bootstrap/js/bootstrap.js', watched: true, included: true, served: true},
      {pattern: 'app/js/myjavascript.js', watched: true, included: true, served: true},
      {pattern: 'test/spec/**/*.js', watched: true, included: true, served: true},
      {pattern: 'test/spec/**/*.html', watched: true, included: false, served: true}
    ],

  });
};

1 个答案:

答案 0 :(得分:0)

您的配置针对的是PhantomJS,它在点击内容时遇到问题。完整的答案在这里:How to ng-click an A directive in a PhantomJS test但缺点是在测试中使用此函数:

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