How do I add DOM elements in jasmine tests without using external html files?
Asked Answered
C

3

19

I'm writing some simple jasmine tests and I'm getting an exception since the code I'm testing is looking for a form that doesn't exist because there's no DOM when testing a js file only: $("form")[0] in the tested js file leads to:

TypeError: $(...)[0] is undefined

I read a bit about jasmine-jquery and realized I can use some html fixture with an external html file. That flow seems quite messy, since all I need to do is only to add an empty valid form so that the test (which focusing on something else) will run, something like <form></form> appending would be enough I think.

At first I thought that sandbox() function will be the solution, but it seems that it creates only divs, and I need a form.

Any simple way to add some elements by using only code in jasmine spec file?

Corroboration answered 11/1, 2013 at 16:2 Comment(0)
C
38

The simplest solution is to add the form to the DOM by yourself in the before block and then delete it in the after block:

describe(function(){
  var form;

  beforeEach(function(){
    form = $('<form>');
    $(document.body).append(form);
  });

  it('your test', function(){


  })

  afterEach(function(){
   form.remove();
   form = null;
  });
});

Also writing your sandbox helper isn't that hard:

function sandbox(html){
  var el;

  beforeEach(function(){
    el = $(html);
    $(document.body).append(el);
  });


  afterEach(function(){
   el.remove();
   el = null;
});
Coben answered 12/1, 2013 at 10:35 Comment(3)
For some reason I thought html appending won't work since I was sure that there's no DOM, only javascript. Your answer seems so trivial. Oh well. @Andreas-KöberleCorroboration
Thank you. This fixed my issue of the focus event handler not firing.Geulincx
How is the sandbox helper called? Do you just call it manually in the describe() block?Kiln
C
3

Another approach is to use jasmine fixture

The concept

Here's one way to think about it:

In jQuery, you give $() a CSS selector and it finds elements on the DOM.

In jasmine-fixture, you give affix() a CSS selector and it adds those elements to the DOM.

This is very useful for tests, because it means that after setting up the state of the DOM with affix, your subject code under test will have the elements it needs to do its work.

Finally, jasmine-fixture will help you avoid test pollution by tidying up and remove everything you affix to the DOM after each spec runs.

See also: SO: dom manipulation in Jasmine test

Campfire answered 28/12, 2014 at 8:45 Comment(1)
best answer by far, fixtures will let you work as in the original htmlPomiferous
Y
0

You should use sandbox() to create a div and create a form element and append to sandbox, this is the safer way to jasmine take control to this fixtures in the DOM.

Yet answered 20/10, 2014 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.