是否可以在JavaScript中模拟document.cookie? [英] Is it possible to mock document.cookie in JavaScript?

查看:136
本文介绍了是否可以在JavaScript中模拟document.cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

document.cookie 就像一个字符串,但它不是一个字符串。引用 Mozilla doc 中的示例:

document.cookie is like a string, but it is not a string. To quote the example from the Mozilla doc:

document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
alert(document.cookie);
// displays: name=oeschger;favorite_food=tripe

如果你试图制作一个模拟cookie只使用一个字符串,你得到相同的结果:

If you tried to make a mock cookie using only a string, you would not get the same results:

var mockCookie = "";
mockCookie = "name=oeschger";
mockCookie = "favorite_food=tripe";
alert(mockCookie);
// displays: favorite_food=tripe

所以,如果你想对模块进行单元测试在cookie上运行,如果你想用这些测试的模拟cookie,你呢? 如何?

So, if you wanted to unit test a module that operates on the cookie, and if you wanted to use a mock cookie for those tests, could you? How?

推荐答案

您可以使用 Cookie创建对象 setter和getter。这是一个非常简单的实现:

You could create an object with a cookie setter and getter. Here is a very simple implementation:

var mock = {
    value_: '', 

    get cookie() {
        return this.value_;
    },

    set cookie(value) {
        this.value_ += value + ';';
    }
};

可能不适用于所有浏览器(尤其是IE)。 更新:仅适用于支持ECMAScript 5的浏览器!

Might not work in all browsers though (especially IE). Update: It only works in browsers supporting ECMAScript 5!

关于getter和setter的更多信息

mock.cookie = "name=oeschger";
mock.cookie = "favorite_food=tripe";
alert(mock.cookie);
// displays: name=oeschger;favorite_food=tripe;

DEMO

这篇关于是否可以在JavaScript中模拟document.cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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