简体   繁体   中英

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

Maybe the issue is that checking if text is selected when a mouseup event occurs is not the best way to do this? 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

So in Jasmine you would spy on window.getSelection and return a string in one case and none in the other. Then you would check that this what should happen in note.placeOver happens.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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