最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I fake a storage event in my jasmine unit tests? - Stack Overflow

programmeradmin4浏览0评论

I'm going to need to handle some storage events.

window.addEventListener('storage', listener);

I'm trying to unit test my code with jasmine.

Simply putting something into localStorage using setItem(key, value) in the test won't work since by design the event won't be raised for the originator of the event.

Using $(window).trigger('storage'... seemed like a good idea to begin with but I don't think it's right.

I've seen posts asking how to mock local storage with spyOn but I can't find any that deal with events.

I'm going to need to handle some storage events.

window.addEventListener('storage', listener);

I'm trying to unit test my code with jasmine.

Simply putting something into localStorage using setItem(key, value) in the test won't work since by design the event won't be raised for the originator of the event.

Using $(window).trigger('storage'... seemed like a good idea to begin with but I don't think it's right.

I've seen posts asking how to mock local storage with spyOn but I can't find any that deal with events.

Share Improve this question asked Aug 26, 2014 at 15:22 GrokodileGrokodile 3,9335 gold badges36 silver badges61 bronze badges 1
  • why don't you pass a mock window? – Daniel A. White Commented Aug 26, 2014 at 15:23
Add a comment  | 

2 Answers 2

Reset to default 25

This did the trick:

window.dispatchEvent(new StorageEvent('storage', {
    key: 'test_key', 
    newValue: 'test_value' 
});

For bonus points in IE too:

var se = document.createEvent('StorageEvent');
se.initStorageEvent('storage', false, false, 'test_key', null, 'test_value', '/', null);
window.dispatchEvent(se);

Sorry to put as answer (don't have rep to comment):

I would suggest to start with answering on the question: "What are you trying to test?"

  • If you are testing your event handler - call it and provide a mock of event
  • If you want to be sure you've attached your handler - spyOn and check that it was attached

As far as I can understand you are writing a unit test - then test your unit and mock all external dependencies. Manually firing events seems more like simulating the browser.

If I'm wrong please explain your situation in more details.

发布评论

评论列表(0)

  1. 暂无评论