ppasler
ppasler

Reputation: 3719

event.preventDefault and jasmine.toHaveBeenTriggeredOn do not work together

I have an object with a click listener and try to write tests for it. I have problems using jasmine expect(event).toHaveBeenTriggered() and it seems the problem is the e.preventDefault statement.

Listener:

$(document).on("click", "input", function (e) {
    e.preventDefault();
    // do something
});

Test:

describe("SomeTest", function () {
    "use strict";

    beforeEach(function () {
        setFixtures("<input />");
    });

    it("should have been triggered", function () {
        var input = $('input');
        var spyEvent = spyOnEvent(input, 'click' );
        $( input ).click();
        expect( spyEvent ).toHaveBeenTriggered();
    });

});

Is there a way to get toHaveBeenTriggered to work or disable preventDefault for testing?

Upvotes: 1

Views: 1782

Answers (1)

ppasler
ppasler

Reputation: 3719

There are special Matchers in jasmine-jquery for this toHaveBeenPreventedOn() and toHaveBeenPrevented()

From the documentation:

var spyEvent = spyOnEvent('#some_element', 'click')
$('#some_element').click(function (event){event.preventDefault();})
$('#some_element').click()
expect('click').toHaveBeenPreventedOn('#some_element')
expect(spyEvent).toHaveBeenPrevented()

Upvotes: 1

Related Questions