Skip to content

Commit

Permalink
feat: chai.spy.callsBackWith implements #65
Browse files Browse the repository at this point in the history
  • Loading branch information
nickcarenza committed Jan 12, 2018
1 parent 6f85d1f commit 2e3b077
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -131,6 +131,15 @@ Better to use arrow function:
const returnTrue = chai.spy(returns => true);
```

### spy.callsBackWith
`chai.spy.callsBackWith` is a helper which creates a function that calls the provided callback function with the provided values:

```js
// or you can create a spy which calls back with some values
const spy = chai.spy.callsBackWith(new Error('foo'));
const spy = chai.spy.callsBackWith(null, {id: 12});
````

### Sandboxes

Sandbox is a set of spies. Sandbox allows to track methods on objects and restore original methods with on `restore` call.
Expand Down
24 changes: 24 additions & 0 deletions lib/spy.js
Expand Up @@ -340,6 +340,30 @@ module.exports = function (chai, _) {
});
};

/**
* # chai.spy.callsBackWith (function)
*
* Creates a spy which automatically calls any passed callback function with the provided values.
*
* var method = chai.spy.callsBackWith(new Error('foo'));
* var method = chai.spy.callsBackWith(null, {id:12});
*
* @param {*} value static value which is returned by spy
* @returns new spy function which calls the
* @api public
*/

chai.spy.callsBackWith = function () {
var args = arguments;
return chai.spy(function(){
callbackFn = arguments[arguments.length-1];
chai.assert(
typeof callbackFn === 'function'
, 'expected ' + callbackFn + ' to be a callback function');
callbackFn.apply(null, args);
});
}

/**
* # spy
*
Expand Down
29 changes: 29 additions & 0 deletions test/spies.js
Expand Up @@ -227,6 +227,35 @@ describe('Chai Spies', function () {
spy().should.equal(value);
});

it('should create spy which calls back with static values', function() {
var value1 = 7;
var value2 = true;
var value3 = {id:4};
var spy = chai.spy.callsBackWith(value1, value2, value3);

var callback = function(arg1, arg2, arg3) {
arg1.should.equal(value1);
arg2.should.equal(value2);
arg3.should.equal(value3);
};

spy.should.be.a.spy;
spy(123, false, callback);
});

it('should know if final argument is a function', function() {
var value = 'foo';
var spy = chai.spy.callsBackWith(value);

spy.should.be.a.spy;
(function(){
spy(3);
}).should.throw(chai.AssertionError);
(function(){
spy();
}).should.throw(chai.AssertionError);
});

describe('.with', function () {
it('should not interfere chai with' ,function () {
(1).should.be.with.a('number');
Expand Down

0 comments on commit 2e3b077

Please sign in to comment.