简体   繁体   English

如何有效测试此JavaScript?

[英]How can I test this JavaScript effectively?

I've written a piece of code which acts on the event that a user highlights some text on a page. 我编写了一段代码,该代码在用户突出显示页面上的某些文本时起作用。 The code works fine (below) but my issue is how to test it effectively? 该代码可以正常工作(如下),但是我的问题是如何有效地对其进行测试? Is there a way of mocking a user selecting text (specifically involving a mouseup event). 有没有一种方法可以模拟用户选择文本(特别是涉及mouseup事件)。

Maybe the issue is that checking if text is selected when a mouseup event occurs is not the best way to do this? 可能的问题是,当发生mouseup事件时检查是否选择了文本不是最好的方法吗? Any insight is appreciated. 任何见解均表示赞赏。

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

Ideally I'd like to be able to trigger this with test code so I can ensure note.placeOverlay() happens 理想情况下,我希望能够使用测试代码触发此操作,以便确保note.placeOverlay()发生

So in Jasmine you would spy on window.getSelection and return a string in one case and none in the other. 因此,在Jasmine中,您将监视window.getSelection并在一种情况下返回一个字符串,而在另一种情况下window.getSelection返回任何字符串。 Then you would check that this what should happen in note.placeOver happens. 然后,您将检查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

Maybe you can show what note.placeOver does, so I can complete the answer. 也许您可以显示note.placeOver功能,所以我可以完成答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM