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.
When you want to mock out all ajax calls across an entire suite, use install() in a beforeEach . Because jasmine-ajax stubs out the global XMLHttpRequest for the page, you'll want to uninstall() in an afterEach so specs or setup that expect to make a real ajax request can.
Creating mock localStorage We can create a mock version of localStorage inside beforeEach() with an object with similar APIs to localStorage itself. }; }); Then we can use spyOn method with and.
In the hook, we call the spyOn method to stub the setBar method and then watch how it's called and the result. We can use the toHaveBeenCalled matcher to check if the function is called. Also, we can use toHaveBeenCalledTimes to check how many times it's been called.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With