Skip to content

Instantly share code, notes, and snippets.

@erinishimoticha
Last active January 7, 2017 08:21
Show Gist options
  • Save erinishimoticha/aa4daa929155f19864c030271e3721f5 to your computer and use it in GitHub Desktop.
Save erinishimoticha/aa4daa929155f19864c030271e3721f5 to your computer and use it in GitHub Desktop.
Thenable Sinon Stubs
'use strict';
const expect = require('chai').expect;
const stubAsPromised = require('./stub-as-promised');
const lib = {
method: () => {}
};
let sinon;
describe('a test', () => {
let myStub;
beforeEach(() => {
setTimeout(() => {
lib.method();
}, 1000);
});
beforeEach(() => {
sinon = require('sinon').sandbox.create();
myStub = stubAsPromised(sinon, lib, 'method');
});
afterEach(() => {
sinon.restore();
});
it('does not get called until after myStub.promise resolves', () => {
return lib.method.promise.then(() => {
expect(lib.method.called).to.equal(true);
expect(lib.method.args[0][0]).to.equal(undefined);
});
});
});
'use strict';
/**
* Wrap a sinon stub in a function which resolves a promise when the stub is called.
*/
module.exports = (sandbox, object, methodName, func) => {
let wrapper;
func = func || function () {};
const promise = new Promise(resolve => {
wrapper = () => {
resolve();
return func.apply(null, arguments);
};
});
const stub = sandbox.stub(object, methodName, wrapper);
stub.promise = promise;
return stub;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment