Override Default Properties with JavaScript

By  on  

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!

The JavaScript

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

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:

// 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!

Recent Features

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

Incredible Demos

  • By
    Duplicate the jQuery Homepage Tooltips

    The jQuery homepage has a pretty suave tooltip-like effect as seen below: The amount of jQuery required to duplicate this effect is next to nothing;  in fact, there's more CSS than there is jQuery code!  Let's explore how we can duplicate jQuery's tooltip effect. The HTML The overall...

  • By
    PHP Woot Checker – Tech, Wine, and Shirt Woot

    If you haven't heard of Woot.com, you've been living under a rock. For those who have been under the proverbial rock, here's the plot: Every day, Woot sells one product. Once the item is sold out, no more items are available for purchase. You don't know how many...

Discussion

  1. Valtteri

    Why not this:

    Object.defineProperty(navigator, 'userAgent', {
        get() {
            return 'WalshBot';
        }
    });

    It’s standard and seems to work fine.

  2. Useful but it should be treated carefully, because what would it happen if the test fails and we don’t reassign the original value?

  3. Interesting as this can be used to invoke functions without any ().

    Here I am counting the number of times a property is requested;

    'use strict';
    
    let phelm = {
      getCount: 0,
      hasStore: ''
    };
    
    phelm.__defineGetter__('is', function() {
      this.getCount ++;
      return 'cool';
    });
    
    console.log(phelm.getCount);
    console.log(phelm.is);
    console.log(phelm.getCount);
    
  4. Hi,

    __defineGetter__ is deprecated.

    Another way: IE9+

    var originalUserAgent = navigator.userAgent;
    
    Object.defineProperty(navigator, 'userAgent', {
      value: 'Walshbot',
      writable: true,
      configurable: true,
      enumerable: true
    })
    
    console.log(navigator.userAgent) // Walshbot 
    
    Object.defineProperty(navigator, 'userAgent', {
      value: originalUserAgent,
      writable: true,
      configurable: true,
      enumerable: true
    })
    
  5. Jason

    Doesn’t seem to work cross-domain, only seems to work in frames with local content.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!