【问题标题】:How can I test this JavaScript effectively?我怎样才能有效地测试这个 JavaScript?
【发布时间】:2013-02-28 00:37:39
【问题描述】:

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

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

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

理想情况下,我希望能够用测试代码触发它,这样我就可以确保 note.placeOverlay() 发生

【问题讨论】:

  • 一个非常初级的方法是在回调函数note.placeOverlay()的末尾执行一个简单的alert(),或者使用console.log('placeOverlay() is executed')
  • 特里:让我澄清一下;我想用代码自动触发事件以进行自动化测试。 Bryan:不是真的,它没有解决事件被mouseup触发的问题
  • 你不能在元素上调用.mouseup() 吗? api.jquery.com/mouseup

标签: javascript jquery testing bdd jasmine


【解决方案1】:

因此,在 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 做了什么,这样我就可以完成答案了。

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多