A simple way to mock calls to the Mandrill API from nodejs tests. It uses the amazing mockery
package.
Mandrill API mocking in Nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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