Javascript 在 Jasmine 测试中测试 DOM 操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7672389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing DOM manipulating in Jasmine test
提问by S?awosz
I'm creating a js widget and first part is to add script width javascript, something like this (example from google analytics):
我正在创建一个 js 小部件,第一部分是添加脚本宽度 javascript,如下所示(来自谷歌分析的示例):
(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?)?
如何用茉莉花测试它(使用夹具?)?
回答by Justin Searls
For setting up HTML fixtures in my specs, I wrote jasmine-fixture. With it, you can do stuff like this:
为了在我的规范中设置 HTML 固定装置,我编写了jasmine-fixture。有了它,你可以做这样的事情:
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.
而afterEach,它会在你之后清理。
For expectations about the state of the DOM, I use jasmine-jquery. It offers a ton of matchers like the one below:
对于 DOM 状态的期望,我使用jasmine-jquery。它提供了大量的匹配器,如下所示:
it('is named Jim', function(){
expect($input).toHaveValue("Jim");
});
回答by Doug Avery
I suppose you could perform your action, then check the href on the first script tag like so:
我想你可以执行你的操作,然后像这样检查第一个脚本标签上的 href :
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.
不过,有兴趣听到更好的方法。用 Jasmine 检查 DOM 总是感觉有点笨拙。
回答by bjornd
For heavy DOM testing with Jasmine you can use Jasmine Headless WebKit.
对于使用Jasmine进行大量 DOM 测试,您可以使用Jasmine Headless WebKit。