Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sanbox): adds support for replacing implementation of object's method #73

Merged
merged 1 commit into from Jun 15, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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