Skip to content

Commit

Permalink
Merge pull request #73 from stalniy/feat/on-stub
Browse files Browse the repository at this point in the history
feat(sanbox): adds support for replacing implementation of object's method
  • Loading branch information
keithamus committed Jun 15, 2017
2 parents b11aeeb + c311f83 commit 2fe7e55
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/spy.js
Expand Up @@ -42,17 +42,20 @@ module.exports = function (chai, _) {
* const array = []
* const spy = chai.spy.sandbox();
* const [push, pop] = spy.on(array, ['push', 'pop']);
*
* spy.on(array, 'push', returns => 1)
*
* @param {Object} object
* @param {String|String[]} method name or methods names to spy on
* @param {Function} [fn] mock implementation
* @returns created spy or created spies
* @api public
*/

Sandbox.prototype.on = function (object, methodName) {
Sandbox.prototype.on = function (object, methodName, fn) {
if (Array.isArray(methodName)) {
return methodName.map(function (name) {
return this.on(object, name);
return this.on(object, name, fn);
}, this);
}

Expand All @@ -69,7 +72,7 @@ module.exports = function (chai, _) {
throw new Error('"' + methodName + '" is already a spy')
}

var method = chai.spy('object.' + methodName, object[methodName]);
var method = chai.spy('object.' + methodName, fn || object[methodName]);
var trackingId = ++spyAmount

this[STATE_KEY][trackingId] = method;
Expand Down
17 changes: 17 additions & 0 deletions test/spies.js
Expand Up @@ -442,6 +442,23 @@ describe('Chai Spies', function () {
chai.spy.on(object, 'push');
}).should.throw(Error)
});

it('should allow to overwrite method implementation', function () {
chai.spy.on(object, 'push', function() {
return 5;
});

object.push().should.equal(5);
});

it('should overwrite all methods with the same implementation', function () {
chai.spy.on(object, ['push', 'pop'], function() {
return 5;
});

object.push().should.equal(5);
object.pop().should.equal(5);
})
});

describe('spy interface', function () {
Expand Down

0 comments on commit 2fe7e55

Please sign in to comment.