Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Feb 18th, 2013  |  syntax: None  |  size: 1.36 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. var someUtilityFunction = () {
  2.     return window.location.search.substring(1);
  3. };
  4.        
  5. test('#1 someUtilityFunction works', function () {
  6.     // setup
  7.     var oldQS = window.location.search;
  8.     window.location.search = '?key1=value1&key2=value2&key3=value3';
  9.  
  10.     var expectedOutput = 'key1=value1&key2=value2&key3=value3';
  11.  
  12.     // test
  13.     equals(someUtilityFunction(),
  14.         expectedOutput,
  15.         'someUtilityFunction works as expected.');
  16.  
  17.     // teardown
  18.     window.location.search = oldQS;
  19. });
  20.        
  21. var customWindow = {
  22.     location: {
  23.         search: "",
  24.         hash: ""
  25.     }
  26. };
  27.        
  28. var someUtilityFunction;
  29.  
  30. (function(window) {
  31.     // window is now shadowed by your local variable
  32.     someUtilityFunction = () {
  33.         return window.location.search.substring(1);
  34.     };
  35. })(customWindow);
  36.        
  37. // first some more preparation for our mock
  38. customWindow.window = customWindow;
  39.  
  40. with(customWindow) {
  41.  
  42.     // this still creates the var in the global scope
  43.     var someUtilityFunction = () {
  44.         // window is a property of customWindow
  45.         return window.location.search.substring(1);
  46.     };
  47.  
  48.     // since customWindow is our scope now
  49.     // this will work also
  50.     someUtilityFunction = () {
  51.         // location is a property of customWindow too
  52.         return location.search.substring(1);
  53.     };
  54.  
  55. }
  56.        
  57. window.location.search.replace(/^?/, "");
  58.        
  59. window.location.substr(1);