如何在不使用外部 html 文件的情况下在 jasmine 测试中添加 DOM 元素? [英] How do I add DOM elements in jasmine tests without using external html files?
问题描述
我正在编写一些简单的 jasmine 测试,但我遇到了一个异常,因为我正在测试的代码正在寻找一个不存在的表单,因为仅在测试 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 文件一起使用.该流程似乎很混乱,因为我需要做的只是添加一个空的有效表单,以便测试(专注于其他内容)运行,例如 <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 文件的情况下在 jasmine 测试中添加 DOM 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!