Guest User

Untitled

a guest
Jun 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. // I needed a basis with which to mock.
  2. function CanYouMockMe(){
  3. this.i_want_stubbed = function(){ return false; };
  4. this.say = function(){ console.log(arguments[0] || "hi!"); };
  5. };
  6.  
  7. // new Object def.
  8. function Foo() {
  9. this.do_something_interesting = function() {
  10. //hard coded dependency... like my ex-wife. :P
  11. var dependency = new CanYouMockMe();
  12. if(dependency.i_want_stubbed() === true) {
  13. return "I've been stubbed!"
  14. } else {
  15. return "I 100% original!";
  16. }
  17. }
  18. }
  19.  
  20. function Mock(){
  21. this.i_want_stubbed = function(){ return true; };
  22. };
  23.  
  24.  
  25. // inherit from the object you wish to mock
  26. // this ensures that any non-stubbed/mocked
  27. // properties will exist on your mock as written;
  28. Mock.prototype = new CanYouMockMe();
  29.  
  30. // see, we got all the cool stuff.
  31. var myMock = new Mock();
  32. myMock.say();
  33. myMock.say("dude!");
  34. console.log(myMock.i_want_stubbed());
  35.  
  36. // see nothing has changed yet.
  37. var myConcrete = new CanYouMockMe();
  38. myConcrete.say();
  39. myConcrete.say("dude!");
  40. console.log(myConcrete.i_want_stubbed());
  41.  
  42. // I want to be able to get it back.
  43. ORIG_CanYouMockMe = CanYouMockMe;
  44.  
  45. // it's clobberin time!
  46. CanYouMockMe = Mock;
  47.  
  48. // changes!
  49. var myConcrete = new CanYouMockMe();
  50. myConcrete.say();
  51. myConcrete.say("dude!");
  52. console.log(myConcrete.i_want_stubbed());
  53.  
  54. //AND FOR MY FINAL TRICK!
  55.  
  56. // it's clobberin time!
  57. CanYouMockMe = ORIG_CanYouMockMe;
  58.  
  59. // AND WE'RE BACK!!!
  60. var myConcrete = new CanYouMockMe();
  61. myConcrete.say();
  62. myConcrete.say("dude!");
  63. console.log(myConcrete.i_want_stubbed());
  64.  
  65. //original foo
  66. var foo = new Foo();
  67. console.log(foo.do_something_interesting());
  68.  
  69. CanYouMockMe = Mock;
  70. //mocked dependency
  71. var foo2 = new Foo();
  72. console.log(foo2.do_something_interesting());
  73.  
  74. //bring it back.
  75. CanYouMockMe = ORIG_CanYouMockMe
  76. var foo3 = new Foo();
  77. console.log(foo3.do_something_interesting());
Add Comment
Please, Sign In to add comment