Testing DOM manipulation with Jasmine
Asked Answered
U

3

25

I'm creating a JS widget and first part is to add script with javascript, something like this (example from google analytics):

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

How to test it with jasmine (using fixtures)?

Ulrike answered 6/10, 2011 at 9:23 Comment(1)
possible duplicate of how to unit test DOM manipulation (with jasmine)Willams
E
24

For setting up HTML fixtures in my specs, I wrote jasmine-fixture. With it, you can do stuff like this:

var $foo, $input;
beforeEach(function(){
  $foo = affix('.foo');
    # appends to the DOM <div class="foo"></div> 
  $input = $foo.affix('input[id="name"][value="Jim"]');
    # appends <input id="name" value="Jim"/> beneath the .foo div

And afterEach, it'll clean up after you.

For expectations about the state of the DOM, I use jasmine-jquery. It offers a ton of matchers like the one below:

it('is named Jim', function(){
  expect($input).toHaveValue("Jim");
});
Errata answered 22/11, 2011 at 13:24 Comment(0)
S
5

I suppose you could perform your action, then check the href on the first script tag like so:

function addGA(){
    var ga = document.createElement('script'); 
    ga.type = 'text/javascript'; ga.async = true;
    ga.src = 
      ('https:' == document.location.protocol ? 'https://ssl' : 'http://www')
      + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(ga, s);
};

Jasmine spec:

 var href = 'http://www.google-analytics.com/ga.js';
 expect(document.getElementsByTagName('script')[0].href).not.toEqual(href);
 addGa();
 expect(document.getElementsByTagName('script')[0].href).toEqual(href);

Would be interested in hearing a better method, though. Checking the DOM with Jasmine always feels a little hacky.

Sediment answered 8/10, 2011 at 19:25 Comment(0)
Z
3

For heavy DOM testing with Jasmine you can use Jasmine Headless WebKit.

Zany answered 6/10, 2011 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.