Created
February 25, 2014 18:08
-
-
Save stash/9214439 to your computer and use it in GitHub Desktop.
sinon mock object play
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*jshint node:true */ | |
| 'use strict'; | |
| var assert = require('assert'); | |
| var sinon = require('sinon'); | |
| var util = require('util'); | |
| function spew(label, o) { | |
| console.log(label, util.inspect(o, {colors:true, depth:null})); | |
| } | |
| function Class() { | |
| this.constructed = true; | |
| } | |
| Class.prototype.foo = function() { | |
| console.log('original foo', this, arguments); | |
| return 'foo'; | |
| }; | |
| Class.prototype.bar = function() { | |
| console.log('original bar', this, arguments); | |
| return 'bar'; | |
| }; | |
| function defaultNever(mock) { | |
| Object.keys(mock.object).forEach(function(property) { | |
| mock.expects(property).never(); | |
| }); | |
| } | |
| var mock = sinon.mock(Class.prototype); | |
| defaultNever(mock); | |
| spew('mock:', mock); | |
| mock.foo = mock.expects('foo').never().once().returns('FOO'); | |
| spew('mocked prototype:', Class.prototype); | |
| var instance = new Class(); | |
| try { | |
| var fooVal = instance.foo(); | |
| console.log('fooVal', fooVal); | |
| assert.equal(fooVal, 'FOO'); | |
| } catch(e) { | |
| console.log('could not call foo', e); | |
| } | |
| try { | |
| var barVal = instance.bar(); | |
| console.log('barVal', barVal); | |
| } catch(e) { | |
| console.log('could not call bar', e); | |
| } | |
| try { | |
| mock.verify(); | |
| } catch(e) { | |
| console.log('verification:', e); | |
| } | |
| mock.restore(); | |
| spew('restored prototype:', Class.prototype); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment