12

I'm writing specs for different test cases for Jasmine and QUnit to compare them and they looked the same before I needed to write a test to check if an event is binded to an element.

Event binding looks like

$('.page').live('click', function() { page_clicked( $(this) ) });

page_clicked is a private method but it calls for a public method of another module.

Here is a Jasmine spec:

it('should bind events to pages', function() {
    spyOn( search, 'get_results' );

    $('.page:eq(0)').trigger('click');

    expect( search.get_results ).toHaveBeenCalled();
});

This test works. Now I'm trying to write the same test for QUnit and can't find anything similar to spyOn. How to write this test for QUnit?

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Daniel J F
  • 1,054
  • 2
  • 15
  • 29

1 Answers1

9

Its cause QUnit doesn't have spies or mocks. But you can use the Sinon.JS mocking framework. Your test should look like this using sinon spy:

var spy = sinon.spy(search, 'get_results');
sinon.assert.calledOnce(spy);
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • Tried to copy/paste your code but `assert(spy.calledOnce)` throws `assert is not defined` and `sinon.assert.called( spy )` throws `expected get_results to have been called at least once but was never called` – Daniel J F Jan 15 '12 at 13:35
  • Ok it was copy/pasted from sinon doku, I fixed it. – Andreas Köberle Jan 15 '12 at 15:12
  • Still doesn't work. `expected get_results to be called once but was called 0 times`. I put an alert after `get_results` call in the `page_clicked` function and the alert prompts, Jasmine test passes but QUnit + SinonJS doesn't. – Daniel J F Jan 15 '12 at 15:26
  • Oh, it works, I just inserted `trigger('click')` in the wrong place. Thanks. – Daniel J F Jan 15 '12 at 16:02