Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I fake a storage event in my jasmine unit tests?

Tags:

javascript

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.

like image 275
Grokodile Avatar asked Aug 26 '14 15:08

Grokodile


People also ask

How do you mock Jasmine?

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.

How to mock localStorage in Angular?

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.

How do you check if a function is called in Jasmine?

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.


1 Answers

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);
like image 143
Grokodile Avatar answered Sep 23 '22 12:09

Grokodile