Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a click event with Jasmine that appends a style sheet to the head

jQuery

$(".theme-picker").click(function () {
      $('head').append('<link rel="stylesheet" href="" type="text/css" media="screen" id="theme_switcher"/>');
});

Jasmine

describe("style.switcher", function() {

beforeEach( function() {
    jasmine.getFixtures().set(
        '<head></head>' +
        '<div class="switcher">' +
          '<a class="theme-picker" title="theme-picker"></a>' +
          '<a class="folder-picker" title="folder-picker"></a>' +
          '<a class="font-picker" title="font-picker"></a>' +
          '<a class="color-picker" title="color-picker"></a>' +
        '</div>' );
  });

it("loads themes switcher link in head", function() {
  $('.theme-picker').trigger('click');
  expect( $('head') ).toContain("theme_switcher");
});
});

I am new to jasmine and the test is currently failing. I am unsure if it is the fixture, the trigger event or something else entirely.

like image 627
coreballs Avatar asked May 30 '12 20:05

coreballs


2 Answers

I think the chosen answer (even though it's by the OP!) is misleading and incorrect. I'm not sure why it would be "poor form" to test the effect that a piece of JavaScript has on some targeted HTML. Often that's the only output that you can use to verify whether a method works.

The test that's used as an example doesn't actually prove anything: of course click was triggered, you just triggered it! What you want to do is prove something that follows from that click, e.g. a change in a DOM or other data structure, which was the original (IMO correct) instinct.

What you want is to use an asynchronous test to wait for a change in the DOM and then give up, similar to the way the Ruby library Capybara works:

it('loads themes switcher link in head', function() {
  $('.theme-picker').trigger('click');

  waitsFor(function() {
    return $('head').contains('theme_switcher');
  }, 'theme switcher never loaded', 10000);
});
like image 102
method Avatar answered Nov 16 '22 10:11

method


Research has shown it is in poor form to test page specific elements.

My current test (passing) is as follows:

describe("zen switcher", function() {

beforeEach( function() {
  loadFixtures('zen_switcher.html');
  spyOnEvent($('.theme-picker'), 'click');
});

it("clicks the .theme-picker", function() {
  $('.theme-picker').click();
  expect('click').toHaveBeenTriggeredOn($('.theme-picker'));
});
});
like image 33
coreballs Avatar answered Nov 16 '22 10:11

coreballs