Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nagyv
Created May 27, 2017 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nagyv/39ebf7975f8a45da33a808bad92f2ea8 to your computer and use it in GitHub Desktop.
Save nagyv/39ebf7975f8a45da33a808bad92f2ea8 to your computer and use it in GitHub Desktop.
Mandrill API mocking in Nodejs

A simple way to mock calls to the Mandrill API from nodejs tests. It uses the amazing mockery package.

const mockery = require('mockery')
const mandrillApiMock = (function mandrillApiMock() {
let sentMail = [];
let mandrillOptions;
function Mandrill(options) {
mandrillOptions = options;
this.messages = {
send: function(data, success, failure) {
sentMail.push(data);
success(null, data);
}
};
}
return {
Mandrill,
mock: {
sentMailCount: () => {
return sentMail.length;
},
sentMail: () => sentMail,
reset: () => {
sentMail = [],
mandrillOptions = null;
},
getOptions: () => {
return mandrillOptions;
}
}
}
}());
before(function(){
// Enable mockery to mock objects
mockery.enable({
warnOnUnregistered: false
})
// Once mocked, any code that calls require('nodemailer') will get our nodemailerMock
mockery.registerMock('mandrill-api/mandrill', mandrillApiMock)
// Make sure anything that uses nodemailer is loaded here, after it is mocked...
})
afterEach(function(){
// Reset the mock back to the defaults after each test
mandrillApiMock.mock.reset()
})
after(function(){
// Remove our mocked nodemailer and disable mockery
mockery.deregisterAll()
mockery.disable()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment