ez-mock
Simple mocking of require modules.
About
I found myself repeating a similar pattern for setting up mocks for unit tests. This package encapsulates that pattern and provides a simple, yet robust, interface.
Example
We want to test a simple module addToDBValue.js
that adds an input value to a database value.
// addToDBValue.jsconst queryDatabase = ; const addToDBValue = { return inputValue + ;} moduleexports = addToDBValue;
The only issue is that database.js
connects to an actual database.
// database.jsconst queryDatabase = { /* database connection and query logic */} moduleexports = queryDatabase;
But we don't want to touch any external systems for a unit test... We can simply mock that required dependency
// test.jsconst Mock TestSubjectMocker = ; // database mock behavior that returns 1 from queryconst databaseMockReturn1 = './database.js' 1; // database mock behavior that returns 2 from queryconst databaseMockReturn2 = './database.js' 2; // set the default database mock to return 1 from queryconst testSubjectMocker = './addToDBValue.js' databaseMockReturn1; // instantiate foo using the default database mocklet addToDBValue = testSubjectMocker;console; // 2console; // 3 // instantiate foo with an override mock behavioraddToDBValue = testSubjectMocker;console; // 3console; // 4
API
Mock(modulePath, functionality)
modulePath: String
The module name, absolute path, or relative path to the module you wish to mock.
functionality : object/function
The functionality you wish to return when require(...)
is called.
TestSubjectMocker(modulePath, defaultMocks)
modulePath: String
The module name, absolute path, or relative path to the module you wish to test with its dependencies mocked.
defaultMocks : Mock/[Mock]
The mock behavior that will always be applied when generating a test subject.
TestSubjectMocker.generateTestSubject(overrideMocks)
defaultMocks : Mock/[Mock]
The mock behavior that overrides the default behavior for this instance of the test subject.
returns : object/function
An instance of the test subject with the mocks applied
TestSubjectMocker.clearMocks()
Clears all registered mocks (even the default mocks)