Skip to content

Instantly share code, notes, and snippets.

@nagyv
Created May 27, 2017
Embed
What would you like to do?
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