如何在不使用外部html文件的情况下在茉莉花测试中添加DOM元素? [英] How do I add DOM elements in jasmine tests without using external html files?
问题描述
我正在编写一些简单的茉莉花测试,我得到一个例外,因为我正在测试的代码正在寻找一个不存在的表单,因为在测试js文件时没有DOM: $(form)[0]
在测试的js文件中导致:
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
我读了一下jasmine-jquery并意识到我可以使用一些外部html文件的html fixture。这个流程看起来很混乱,因为我只需要添加一个空的有效表单,以便测试(专注于其他内容)将运行,例如< form>< / form> ;
追加就足够了。
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.
起初我认为sandbox()函数将是解决方案,但它似乎创造了只有div,我需要一个表单。
At first I thought that sandbox() function will be the solution, but it seems that it creates only divs, and I need a form.
通过仅使用jasmine规范文件中的代码添加一些元素的简单方法?
Any simple way to add some elements by using only code in jasmine spec file?
推荐答案
最简单的解决方案是在before块中自己将表单添加到DOM中,然后在after块中删除它:
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;
});
这篇关于如何在不使用外部html文件的情况下在茉莉花测试中添加DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!