Skip to content

Instantly share code, notes, and snippets.

@aclave1
Last active August 29, 2015 14:05
Show Gist options
  • Save aclave1/ec9ba843a3b6ffcc31ac to your computer and use it in GitHub Desktop.
Save aclave1/ec9ba843a3b6ffcc31ac to your computer and use it in GitHub Desktop.
Unopinionated promise mocking
describe('An object which relies on promises', function () {
it('Should pass if provided the proper parameters', function () {
/**
* our real object would normally depend on promiseDependency,
* but we're replacing it with our mock promise chain here.
*/
sut.promiseDependency = PromiseMocks.ResolveMock();
var params = {
name : 'alex'
};
sut.doLongRunningWork(params);
expect(params.name).to.equal('alex changed');
});
});
describe('An object which relies on promises', function () {
it('Should pass if provided the proper parameters', function () {
sut.promiseDependency = PromiseMocks.RejectMock();
var params = {
name : 'alex'
};
expect(function(){
sut.doLongRunningWork(params);
}).to.throw();
});
});
"use strict";
module.exports = {
//creates a function which returns a fake promise that always resolves
ResolveMock: function () {
return function(params){
var promise = {
then : function (cb) {
cb(params);
return this;
},
catch: function (cb) {
//dont call the cb
return this;
},
done : function (cb) {
cb();
}
};
return promise;
};
},
//creates a function which returns a fake promise that always rejects
RejectMock : function () {
return function(error){
var promise = {
then : function (cb) {
return this;
},
catch: function (cb) {
cb(error);
return this;
},
done : function (cb) {
cb();
}
};
return promise;
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment