Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // I needed a basis with which to mock.
- function CanYouMockMe(){
- this.i_want_stubbed = function(){ return false; };
- this.say = function(){ console.log(arguments[0] || "hi!"); };
- };
- // new Object def.
- function Foo() {
- this.do_something_interesting = function() {
- //hard coded dependency... like my ex-wife. :P
- var dependency = new CanYouMockMe();
- if(dependency.i_want_stubbed() === true) {
- return "I've been stubbed!"
- } else {
- return "I 100% original!";
- }
- }
- }
- function Mock(){
- this.i_want_stubbed = function(){ return true; };
- };
- // inherit from the object you wish to mock
- // this ensures that any non-stubbed/mocked
- // properties will exist on your mock as written;
- Mock.prototype = new CanYouMockMe();
- // see, we got all the cool stuff.
- var myMock = new Mock();
- myMock.say();
- myMock.say("dude!");
- console.log(myMock.i_want_stubbed());
- // see nothing has changed yet.
- var myConcrete = new CanYouMockMe();
- myConcrete.say();
- myConcrete.say("dude!");
- console.log(myConcrete.i_want_stubbed());
- // I want to be able to get it back.
- ORIG_CanYouMockMe = CanYouMockMe;
- // it's clobberin time!
- CanYouMockMe = Mock;
- // changes!
- var myConcrete = new CanYouMockMe();
- myConcrete.say();
- myConcrete.say("dude!");
- console.log(myConcrete.i_want_stubbed());
- //AND FOR MY FINAL TRICK!
- // it's clobberin time!
- CanYouMockMe = ORIG_CanYouMockMe;
- // AND WE'RE BACK!!!
- var myConcrete = new CanYouMockMe();
- myConcrete.say();
- myConcrete.say("dude!");
- console.log(myConcrete.i_want_stubbed());
- //original foo
- var foo = new Foo();
- console.log(foo.do_something_interesting());
- CanYouMockMe = Mock;
- //mocked dependency
- var foo2 = new Foo();
- console.log(foo2.do_something_interesting());
- //bring it back.
- CanYouMockMe = ORIG_CanYouMockMe
- var foo3 = new Foo();
- console.log(foo3.do_something_interesting());
Add Comment
Please, Sign In to add comment