我可以在茉莉花单元测试中伪造存储事件吗? [英] Can I fake a storage event in my jasmine unit tests?

查看:76
本文介绍了我可以在茉莉花单元测试中伪造存储事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将需要处理一些存储事件。

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

window.addEventListener('storage', listener);

我正在尝试使用jasmine对我的代码进行单元测试。

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

只需在测试中使用 setItem(key,value)将某些内容放入 localStorage 因为按设计工作,不会为活动的发起人筹集活动。

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.

使用 $(窗口).trigger('storage' ... 开始时似乎是一个好主意,但我认为这不对。

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

我看过帖子询问如何使用 spyOn 模拟本地存储,但我找不到任何处理事件。

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

推荐答案

这就是诀窍:

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

对于IE中的奖励积分:

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

这篇关于我可以在茉莉花单元测试中伪造存储事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆