如何有效地测试这个JavaScript?

时间:2013-02-28 00:37:40

标签: javascript jquery testing bdd jasmine

我编写了一段代码,用于处理用户突出显示页面上某些文本的事件。代码工作正常(下面),但我的问题是如何有效地测试它?有没有办法嘲笑用户选择文本(特别是涉及mouseup事件)。

问题可能是在mouseup事件发生时检查是否选择了文本不是最好的方法吗?任何见解都表示赞赏。

var note = {
  mouseHandler : function(e){
    selection = window.getSelection();
      if (selection.toString() !== '') {
       note.selection = selection;
       note.setAttributes();
       note.hideOverlay();
       note.placeOverlay();
    }
 }
}

理想情况下,我希望能够使用测试代码触发此功能,以便确保note.placeOverlay()发生

1 个答案:

答案 0 :(得分:0)

所以在Jasmine你会窥探window.getSelection并在一个案例中返回一个字符串而在另一个案例中没有一个字符串。然后你会检查note.placeOver中发生的事情。

spyOn(window, 'getSelection').andReturn('someString')
note.mouseHandler();
//test what you expect here


spyOn(window, 'getSelection').andReturn('')
note.mouseHandler();
//test that nothings happens here

也许你可以展示note.placeOver做了什么,所以我可以完成答案。