How do I mock ES modules in NodeJS?


Say I've implemented a module as follows:

import { foo } from 'dep1'

export const bar = () => foo()

How would I mock dep1 so I can unit test bar?

One possible approach could use ES module loader hooks.

Say that dep1 contains the working code and we want to mock it. I would create a file called mymodule.mocks.mjs where I would mock foo:

// Regular mymodule.mjs
import { foo } from 'dep1'

export const bar = () => foo()

// Mocked mymodule.mocks.mjs

// dep1.foo() returns string
export const bar = () => 'whatever'

Now we should be able to load mymodule.mocks.mjs when mymodule.mjs is requested during a test run.

So we implement testModuleLoader.mjs

Here's a custom module loader hook that implements the *.mocks.mjs convention:

import { existsSync } from 'fs'
import { dirname, extname, basename, join } from 'path'
import { parse } from 'url'

// The 'specifier' is the name or path that we provide
// when we import a module (i.e. import { x } from '[[specifier]]')
export function resolve (
   specifier,
   parentModuleURL,
   defaultResolver
) {
   // For built-ins
   if ( !parentModuleURL )
      return defaultResolver ( specifier, parentModuleURL )

   // If the specifier has no extension we provide the
   // Michael Jackson extension as the default one
   const moduleExt = extname ( specifier ) || '.mjs'
   const moduleDir = dirname ( specifier )
   const { pathname: parentModulePath } = parse (
      parentModuleURL
   )
   const fileName = basename ( specifier, moduleExt )

   // We build the possible mocks' module file path
   const mockFilePath = join (
      dirname ( parentModulePath ),
      moduleDir,
      `${fileName}.mocks${moduleExt}`
   )

   // If there's a file which ends with '.mocks.mjs'
   // we resolve that module instead of the regular one
   if ( existsSync ( mockFilePath ) )
      return defaultResolver ( mockFilePath, parentModuleURL )

   return defaultResolver ( specifier, parentModuleURL )
}

Using it

It's just about providing it to node:

node --experimental-modules --loader ./path/to/testModuleLoader.mjs ./path/to/app.mjs

Learn more about ES module loader hooks.