+ ██╗
+ ██████╗ ███████╗ █████═████╗ ██████╗ ██████╗██║ ██╗
+██╔═══██╗██╔═════╝██╔══██╔══██╗██╔═══██╗██╔════╝██║ ██╔╝
+████████║╚██████╗ ██║ ██║ ██║██║ ██║██║ ██████╔╝
+██╔═════╝ ╚════██╗██║ ██║ ██║██║ ██║██║ ██╔══██╗
+╚███████╗███████╔╝██║ ██║ ██║╚██████╔╝╚██████╗██║ ╚██╗
+ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝
esmock provides native ESM import and globals mocking for unit tests. Use examples below as a quick-start guide, see the descriptive and friendly esmock guide here, or browse esmock's test runner examples.
Note: For versions of node prior to v20.6.0, "--loader" command line arguments must be used with esmock
as demonstrated in the wiki. Current versions of node do not require "--loader".
esmock
has the below signature
await esmock(
'./to/module.js',
{ ...childmocks },
{ ...globalmocks })
esmock
examples
import test from 'node:test'
import assert from 'node:assert'
import esmock from 'esmock'
test('package, alias and local file mocks', async () => {
const cookup = await esmock('../src/cookup.js', {
addpkg: (a, b) => a + b,
'#icon': { coffee: '☕', bacon: '🥓' },
'../src/breakfast.js': {
default: () => ['coffee', 'bacon'],
addSalt: meal => meal + '🧂'
}
})
assert.equal(cookup('breakfast'), '☕🥓🧂')
})
test('full import tree mocks —third param', async () => {
const { getFile } = await esmock('../src/main.js', {}, {
fs: { readFileSync: () => 'returned to 🌲 every caller in the tree' }
})
assert.equal(getFile(), 'returned to 🌲 every caller in the tree')
})
test('mock fetch, Date, setTimeout and any globals', async () => {
const { userCount } = await esmock('../Users.js', {
'../req.js': await esmock('../req.js', {
import: {
fetch: async () => ({
status: 200,
json: async () => [['jim','😄'],['jen','😊']]
})
}
})
})
assert.equal(await userCount(), 2)
})
test('mocks "await import()" using esmock.p', async () => {
const doAwaitImport = await esmock.p('../awaitImportLint.js', {
eslint: { ESLint: cfg => cfg }
})
assert.equal(await doAwaitImport('cfg🛠️'), 'cfg🛠️')
})
test('esmock.strict mocks', async () => {
const pathWrapper = await esmock.strict('../src/pathWrapper.js', {
path: { dirname: () => '/path/to/file' }
})
assert.rejects(() => pathWrapper.basename('/dog.🐶.png'), {
name: 'TypeError',
message: 'path.basename is not a function'
})
})