Question

I'm having a bit of trouble finding a proper way of using jasmine-jquery to test, if following event is correctly triggered

$(document).on('click', '[data-test]', function(e) {
    ...
});

basically I want to write 2 tests that should look somewhat like this (all the ????? parts are the ones that are a mystery to me):

spyOnEvent(?????????????, 'click');
var fixture = setFixtures('<a data-test="whatever"></a> <a class="dummy"></a>');
var $elem = fixture.find('a[data-test="whatever"]');
var $dummy = fixture.find('.dummy');

it('should be triggered', function() {
    $elem.click();
    expect('click').toHaveBeenTriggeredOn(?????);
});

it('should not be triggered', function() {
    $dummy.click();
    expect('click').not.toHaveBeenTriggeredOn(?????);
});

Hope someone out there can help me out on this one =) cheers

Was it helpful?

Solution

The problem is that toHaveBeenTriggeredOn will be true in both cases cause you trigger the click in your test. Also this is not what you want to test. You should test that the click handler was fired. Normally that will be done by testing the result of the click handler function. For example that a class has changed.

$(document).on('click', '[data-test]', function(e) {
   $(this).addClass('test')
});

var fixture = setFixtures('<a data-test="whatever"></a> <a class="dummy"></a>');
var $elem = fixture.find('a[data-test="whatever"]');
var $dummy = fixture.find('.dummy');

it('should be triggered', function() {
    $elem.click();
    expect($elem.hasClass()). toBeTruthy();
});

it('should not be triggered', function() {
    $dummy.click();
    expect(dummy.hasClass()).toBeFalsy();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top