在Jasmine测试中测试DOM操作

Sła*_*osz 24 javascript unit-testing jasmine

我正在创建一个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);
})();
Run Code Online (Sandbox Code Playgroud)

如何用茉莉花测试它(使用固定装置?)?

Jus*_*rls 23

为了在我的规格中设置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
Run Code Online (Sandbox Code Playgroud)

之后,它会在你之后清理干净.

对于DOM的状态的期望,我使用jasmine-jquery.它提供了大量的匹配器,如下所示:

it('is named Jim', function(){
  expect($input).toHaveValue("Jim");
});
Run Code Online (Sandbox Code Playgroud)


Dou*_*ery 5

我想您可以执行您的操作,然后检查第一个脚本标记上的 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);
};
Run Code Online (Sandbox Code Playgroud)

茉莉花规格:

 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);
Run Code Online (Sandbox Code Playgroud)

不过,我有兴趣听到更好的方法。使用 Jasmine 检查 DOM 总是感觉有点古怪。


bjo*_*rnd 3

对于使用 Jasmine 进行大量 DOM 测试,您可以使用Jasmine Headless WebKit