Gathering detailed insights and metrics for nodemailer-mock
Gathering detailed insights and metrics for nodemailer-mock
Gathering detailed insights and metrics for nodemailer-mock
Gathering detailed insights and metrics for nodemailer-mock
nodemailer-mock-transport
mock-mailer for putting tests around services that use node-mailer
@eclass/nodemailer-mock
Mock nodemailer module for testing
mock-nodemailer
Mock nodemailer in tests
@dword-design/tester-plugin-nodemailer-mock
<!-- TITLE/ --> # @dword-design/tester-plugin-nodemailer-mock <!-- /TITLE -->
npm install nodemailer-mock
Typescript
Module System
Node Version
NPM Version
TypeScript (97.46%)
JavaScript (2.43%)
Handlebars (0.11%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
27 Stars
158 Commits
14 Forks
2 Watchers
2 Branches
8 Contributors
Updated on Jun 01, 2025
Latest Version
2.0.9
Package Id
nodemailer-mock@2.0.9
Unpacked Size
46.05 kB
Size
10.32 kB
File Count
8
NPM Version
10.8.3
Node Version
20.16.0
Published on
Jun 01, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
1
23
Easy as pie nodemailer
mock for unit testing your Node.js applications.
npm install nodemailer-mock --save-dev
yarn add -D nodemailer-mock
Depending on your mock configuration nodemailer-mock
may, or may not, have access to nodemailer
when it is loaded. For example, using mockery
you can replace nodemailer
with require('nodemailer-mock')
, however in jest
you will need to inject nodemailer
using module.exports = require('nodemailer-mock').getMockFor(require('nodemailer'));
Use with test suites like jest
and mocha
. There are some special methods available on the mocked module to help with testing. They are under the .mock
key of the mocked nodemailer
.
NodemailerMock.mock
functionsreset: () => void
getSentMail: () => Mail.Options[]
getCloseCallCount: () => number
transporter.close()
was called across all instancessetShouldFailOnce: (isSet?: boolean) => void
transporter.sendMail()
or transport.send()
isShouldFailOnce: () => boolean
setShouldFailOnce(?)
setShouldFail: (isFail?: boolean) => void
transporter.sendMail()
or transport.send()
true
, return errorfalse
, return successisShouldFail: () => boolean
setShouldFail()
setShouldFailCheck: (check: CheckMailMessageOrNull) => void
transporter.sendMail()
or transport.send()
true
, return errorfalse
, return successtype CheckMailMessageOrNull = ((email: MailMessage) => boolean) | null
getShouldFailCheck: () => CheckMailMessageOrNull
MailMessage
or null
if it is not setsetMockedVerify: (isMocked: boolean) => void
transport.verify()
should be mocked or passed through to nodemailer
, defaults to true
.
true
, use a mocked callbackfalse
, pass through to a real nodemailer
transportisMockedVerify: () => boolean
setMockedVerify(?)
setMockedClose: (isMocked: boolean) => void
transporter.close()
should be passed through to the underlying transport, defaults to true
.isMockedClose: () => boolean
true
the underlying transport is not used, when false
the call is passed through.setSuccessResponse: (response: string) => void
transporter.sendMail()
or transport.send()
getSuccessResponse: () => string
setFailResponse: (error: Error) => void
Error
that is returned in the callback for transporter.sendMail()
or transport.send()
getFailResponse: () => Error
Error
valuescheduleIsIdle: (isIdle: boolean, timeout: number) => void
transporter.isIdle()
instancessetIsIdle: (isIdle: boolean) => void
transporter.isIdle()
instancessetUnmockedUsePlugins: (isUnmockUsePlugins: boolean) => void
default false
transporter.use()
be run outside the mock?isUnmockedUsePlugins: () => boolean
setUnmockedUsePlugins(?)
NodemailerMockTransporter.mock
functionsgetPlugins: () => { [key: string]: Mail.PluginFunction<Mail.Options>[] }
transporter.use()
as arrays, keyed by stepgetCloseCallCount: () => number
close()
has been called on this transporter. this number is not reset with the mock.setIdle(isIdle: boolean): void
transporter.isIdle()
and emits an idle
event when the isIdle
argument is true
.The mocked module behaves in a similar fashion to other transports provided by nodemailer
.
setup test
1const nodemailermock = require('nodemailer-mock'); 2const transport = nodemailermock.createTransport(); 3 4// the email you want to send 5const email = ... // <-- your email here
use nodestyle callbacks
1// send with nodestyle callback 2transport.sendMail(email, function(err, info) { 3 if (err) { 4 return console.log('Error!', err, info); 5 } 6 return console.log('Success!', info); 7} 8 9// verify with nodestyle callback 10transport.verify(function(err, success) { 11 if (err) { 12 return console.log('Error!', err); 13 } 14 return console.log('Success!', success); 15});
use promises
1// send with promises 2transport.sendMail(email) 3 .then(function(info) { 4 console.log('Success!', info); 5 }) 6 .catch(function(err) { 7 console.log('Error!', err); 8 }); 9 10// verify with promises 11transport.verify() 12 .then(function(success) { 13 console.log('Success!', success); 14 }); 15 .catch(function(err) { 16 console.log('Error!', err); 17 });
use async/await
1// send an email with async / wait 2try { 3 const info = await transport.sendMail(email); 4} catch (err) { 5 console.log("Error!", err); 6} 7 8// verify with async / wait 9try { 10 const info = await transport.verify(); 11} catch (err) { 12 console.log("Error!", err); 13}
To use nodemailer-mock
in your tests you will need to mock nodemailer
with it. There are working examples using jest
and mocha
in the ./examples/
folder of the project. The jest
code is in ./examples/__mocks__
and ./examples/__tests__
, and the mocha
tests are in ./examples/test
. Run the examples with npm run example:jest
and npm run example:mocha
. Both JavaScript and TypeScript example tests are provided.
To mock nodemailer
using jest
create a file called ./__mocks__/nodemailer.js
that exports the mocked module:
1/** 2 * Jest Mock 3 * ./__mocks__/nodemailer.js 4 **/ 5// load the real nodemailer 6const nodemailer = require("nodemailer"); 7// pass it in when creating the mock using getMockFor() 8const nodemailermock = require("nodemailer-mock").getMockFor(nodemailer); 9// export the mocked module 10module.exports = nodemailermock;
Once the mock file is created all calls to nodemailer
from your tests will return the mocked module. To access to mock functions, just load it in your test file.
1/** 2 * Jest Test 3 * ./__tests__/my-test.js 4 **/ 5const { mock } = require("nodemailer"); 6 7test("Send an email using the mocked nodemailer", async () => { 8 /* ... run your tests that send emails here */ 9 10 // check the mock for our sent emails 11 const sentEmails = mock.getSentMail(); 12 // there should be one 13 expect(sentEmails.length).toBe(1); 14 // and it should match the to address 15 expect(sentEmails[0].to).toBe("justin@to.com"); 16});
Using typescript you can coerce the NodemailerMock type.
1/** 2 * Jest Test 3 * ./__tests__/my-test.js 4 **/ 5import { expect, test } from "@jest/globals"; 6// 'nodemailer' is automatically mocked in ./__mocks__/nodemailer.js 7import * as nodemailer from "nodemailer"; 8import { NodemailerMock } from "nodemailer-mock"; 9const { mock } = nodemailer as unknown as NodemailerMock; 10 11test("Send an email using the mocked nodemailer + typescript", async () => { 12 /* ... run your tests that send emails here */ 13 14 // check the mock for our sent emails 15 const sentEmails = mock.getSentMail(); 16 // there should be one 17 expect(sentEmails.length).toBe(1); 18 // and it should match the to address 19 expect(sentEmails[0].to).toBe("justin@to.com"); 20});
Here is an example of using a mocked nodemailer
class in a mocha
test using mockery
. Make sure that any modules that require()
's a mocked module must be called AFTER the module is mocked or node will use the unmocked version from the module cache. Note that this example uses async/await
. See the module tests for additional example code.
1/** 2 * Mocha Test / Mockery Mock 3 * ./test/my-test.js 4 **/ 5const { expect } = require('chai'); 6const mockery = require('mockery'); 7const nodemailermock = require('nodemailer-mock'); 8 9describe('Tests that send email', async () { 10 11 /* This could be an app, Express, etc. It should be 12 instantiated *after* nodemailer is mocked. */ 13 let app = null; 14 15 before(async () { 16 // Enable mockery to mock objects 17 mockery.enable({ 18 warnOnUnregistered: false, 19 }); 20 21 /* Once mocked, any code that calls require('nodemailer') 22 will get our nodemailermock */ 23 mockery.registerMock('nodemailer', nodemailermock) 24 25 /* 26 ################## 27 ### IMPORTANT! ### 28 ################## 29 */ 30 /* Make sure anything that uses nodemailer is loaded here, 31 after it is mocked just above... */ 32 const moduleThatRequiresNodemailer = require('module-that-requires-nodemailer'); 33 34 }); 35 36 afterEach(async () { 37 // Reset the mock back to the defaults after each test 38 nodemailermock.mock.reset(); 39 }); 40 41 after(async () { 42 // Remove our mocked nodemailer and disable mockery 43 mockery.deregisterAll(); 44 mockery.disable(); 45 }); 46 47 it('should send an email using nodemailer-mock', async () { 48 // call a service that uses nodemailer 49 const response = ... // <-- your email code here 50 51 // a fake test for something on our response 52 expect(response.value).to.equal('value'); 53 54 // get the array of emails we sent 55 const sentMail = nodemailermock.mock.getSentMail(); 56 57 // we should have sent one email 58 expect(sentMail.length).to.equal(1); 59 60 // check the email for something 61 expect(sentMail[0].property).to.equal('foobar'); 62 }); 63 64 it('should fail to send an email using nodemailer-mock', async () { 65 // tell the mock class to return an error 66 const err = new Error('My custom error'); 67 nodemailermock.mock.setShouldFailOnce(); 68 nodemailermock.mock.setFailResponse(err); 69 70 // call a service that uses nodemailer 71 var response = ... // <-- your code here 72 73 // a fake test for something on our response 74 expect(response.error).to.equal(err); 75 }); 76 77 /* this will not work with jest as all nodemailers are mocked */ 78 it('should verify using the real nodemailer transport', async () { 79 // tell the mock class to pass verify requests to nodemailer 80 nodemailermock.mock.setMockedVerify(false); 81 82 // call a service that uses nodemailer 83 var response = ... // <-- your code here 84 85 /* calls to transport.verify() will be passed through, 86 transporter.send() is still mocked */ 87 }); 88});
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
3 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 5
Details
Reason
3 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 2
Reason
Found 3/25 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-07-14
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More