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

coreballs picture coreballs · May 30, 2012 · Viewed 20.6k times · Source

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.

Answer

method picture method · Jul 25, 2012

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