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.
2 Answers
Reset to default 25This 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.
window
? – Daniel A. White Commented Aug 26, 2014 at 15:23