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

此生再无相见时 提交于 2019-11-30 06:42:01
Andreas Köberle

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!