Node.js Mocks Are Easy & Don’t Need a Special Package

There seems to be a node package for nearly every conceivable need, and so I had assumed that mocking–creating modules that exposed the same API as another module, but behaved in a predictable and controllable way so you can test another component–was going to be as simple as npm install . But the packages I found seemed overly complicated, poorly documented, and didn’t really work very well. So I tried the simplest solution I could think of:
1) In your test config.js, create an entry for mock modules, then create an entry for every module you need to mock, like:

mockModules: {
smtpMail: 'app/tests/mock_modules/smtpMailMock.js',
awsMail: 'app/tests/mock_modules/awsMailMock.js'
}

2) In your other environments, make similar entries, pointing to either the mock module or the real module as needed.
3) For each module that requires one of these mockable modules, just use a variable name, like:
var config require(‘config’);
var smtpMail require(config.mockModules.smtpMail);

This is working well for me, and I haven’t hit any downside. Obviously, config needs to be defined before it’s used. Everything is managed through the config, and that’s the only place you need to make changes between different environments.

Advertisements

About jeffmershon

Director of Program Management at SiriusXM.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s