Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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