Skip to content

feat: separate local/global import mocks - #360

Merged
iambumblehead merged 4 commits into
mainfrom
feat/import-local-global
Oct 26, 2026
Merged

iambumblehead merged 4 commits into
mainfrom
feat/import-local-global

Conversation

@tommy-mitchell

Copy link
Copy Markdown
Collaborator

Closes #355

Adds support for having separate global-level import mocks on defs and gdefs:

const hostObjects = await esmock('../local/usesImportObjects.js', {
'../local/exampleMJS.mjs': () => 'second mocked',
import: {
Date: { now: () => 123456789012 },
fetch: () => ({ res: 404 })
}
}, {
'../local/exampleMJS.mjs': () => 'other import',
import: {
Date: { now: () => 123456789098 },
setTimeout: fn => fn(),
fetch: () => ({ res: 200 })
}
})

If both are set, the mocks in gdefs are merged with the ones in defs, with the latter taking precedent.

@iambumblehead

Copy link
Copy Markdown
Owner

is this PR complete? If so, one question I have is about the line that looks like this

    // distinguishes global mocks from local mocks of the same specifier
    scope === 'global' ? 'esmkScope=g' : ''

does it alter the behaviour in any way or is it there for debugging things and looking at the url?

@iambumblehead

Copy link
Copy Markdown
Owner

the test passes with surprisingly few changes, imo. nice PR

@iambumblehead

Copy link
Copy Markdown
Owner

I cloned it and removed this scope === 'global' ? 'esmkScope=g' : '' and see that the test fails without it. I think I understand it...

@iambumblehead

Copy link
Copy Markdown
Owner

It looks good to me

@iambumblehead

Copy link
Copy Markdown
Owner

coverage shows 100% after removing the uncovered line

@iambumblehead
iambumblehead merged commit 3f613bf into main Oct 26, 2026
9 checks passed
@iambumblehead
iambumblehead deleted the feat/import-local-global branch October 26, 2026 00:06
@tommy-mitchell

Copy link
Copy Markdown
Collaborator Author

The global scope line is to differentiate between the two import keys:

esmock/src/esmockModule.js

Lines 121 to 122 in dd12eda

// distinguishes global mocks from local mocks of the same specifier
scope === 'global' ? 'esmkScope=g' : '',

Otherwise they'd overlap on an individual module's replacement string.

(Admittedly I had originally tried to use a separate key for gdefs (e.g. a gimport), but claude pointed out the failure without the scope)

@iambumblehead

Copy link
Copy Markdown
Owner

imo this was a tricky PR thank you for resolving this and in such a way that it appears effortless/easy. I'll publish soonish after getting an auth key from npm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Should the import global module support separate mocks for local/global modules?

3 participants