使用JavaScript覆盖默认属性

Unit testing with client side JavaScript is something you don't do until you're made to.  Of course unit testing is important but let's be honest:  most people are just happy that their code works, right?  Anyways, fast forward to a world where unit testing is normal and we have a problem to solve:  overriding native browser property values for the sake of unit testing.  The following is an easy strategy for overriding default browser property values!

使用客户端JavaScript进行单元测试是您必须要做的事情。 当然,单元测试很重要,但说实话:大多数人都为自己的代码起作用感到高兴,对吗? 无论如何,请进入一个正常的单元测试世界,我们要解决一个问题:为了进行单元测试而覆盖本机浏览器属性值。 以下是覆盖默认浏览器属性值的简单策略!

JavaScript (The JavaScript)

You can't successfully override all properties with a simple statement; let's use navigator.userAgent for example:

您无法通过简单的语句成功覆盖所有属性; 让我们使用navigator.userAgent为例:


console.log(navigator.userAgent);
// >> Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

// Try to set that value -- will be unsuccessful
navigator.userAgent = 'Walshbot';

console.log(navigator.userAgent);
// >> Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36


Overriding the navigator.userAgent can be useful for the purposes of unit and functional testing, so how can we successfully change that value?  With Object.defineProperty:

覆盖navigator.userAgent可以用于单元和功能测试,那么我们如何成功更改该值? 使用Object.defineProperty


// Store the original value
var originalUserAgent = navigator.userAgent;

// Override!
Object.defineProperty(navigator, 'userAgent', {
    get: function() {
        return 'WalshBot';
    }
});

// (Run your tests here)

// Set the value back to original
Object.defineProperty(navigator, 'userAgent', {
    get: function() {
        return originalUserAgent;
    }
});


Within the snippet above, we save the original Object.defineProperty value, override it briefly, then set the value back to the original.  Object.defineProperty is very useful, especially when you consider that the second argument is a function -- you can execute any logic within that function to return the proper value at the time it's requested!

在上面的代码段中,我们保存了原始的Object.defineProperty值,对其进行了短暂覆盖,然后将其设置回原始值。 Object.defineProperty非常有用,尤其是当您认为第二个参数是一个函数时,可以在该函数中执行任何逻辑以在请求时返回正确的值!

翻译自: https://davidwalsh.name/defineproperty

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值