使用Jasmine测试DOM操作

25

我正在创建一个JS小部件,第一部分是使用JavaScript添加脚本,类似于这样(来自Google Analytics的示例):

(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);
})();
如何使用 jasmine(使用 fixtures)进行测试?

可能是[如何使用Jasmine进行DOM操作单元测试]的重复问题(https://dev59.com/a2Qo5IYBdhLWcg3wUN3Y)。 - Gajus
3个回答

24

为了在我的规格说明中设置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

并且在执行完 afterEach 后,它会帮你清理干净。

对于关于 DOM 状态的期望,我使用 jasmine-jquery。它提供了很多像下面这个的匹配器:

it('is named Jim', function(){
  expect($input).toHaveValue("Jim");
});

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

Jasmine规范:

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

我很想听听更好的方法。然而,使用Jasmine检查DOM总感觉有些hacky。


3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,