Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update types addl options #135

Merged
merged 2 commits into from
Aug 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"no-return-assign": 0,
"no-use-before-define": [2, "nofunc"],
"no-nested-ternary": 0,
"array-bracket-spacing": [2, "always"],
"array-bracket-spacing": [2, "never"],
"prefer-destructuring": 2,
"class-methods-use-this": 0,
"no-confusing-arrow": 0
Expand Down
2 changes: 2 additions & 0 deletions src/esmock.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ declare namespace esmock {
interface Options {
partial?: boolean | undefined;
purge?: boolean | undefined;
isPackageNotFoundError?: boolean | undefined;
parent?: string | undefined;
}

/**
Expand Down
45 changes: 20 additions & 25 deletions src/esmock.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,24 @@ import {
esmockCache
} from './esmockCache.js'

const argsToObj = args => {
// Distinguish between the two overloads; see esmock.d.ts.
let modulePath, parent, mockDefs, globalDefs, opt
if (typeof args[1] === "string") {
[ modulePath, parent, mockDefs, globalDefs, opt ] = args
} else {
[ modulePath, mockDefs, globalDefs, opt ] = args
}
return { modulePath, parent, mockDefs, globalDefs, opt }
// this function normalizes different "overloaded" args signatures, returning
// one predictable args list. ex,
// [modulepath, mockdefs, globaldefs, opts]
// -> [modulepath, mockdefs, globaldefs, opts]
// [modulepath, parent, mockdefs, globaldefs, opts]
// -> [modulepath, mockdefs, globaldefs, { ...opts, parent }]
const argsnormal = (args, argsextra, parent) => {
parent = typeof args[1] === 'string' && args[1]
args = parent ? [args[0], ...args.slice(2)] : args
args[3] = { parent, ...args[3], ...(argsextra && argsextra[0]) }
args[4] = (argsextra && argsextra[1]) || args[4]

return args
}

const _esmock = async (argsObj, err) => {
const { modulePath, parent, mockDefs, globalDefs, opt = {} } = argsObj

const calleePath = (parent || err.stack.split('\n')[2])
const esmock = async (...args) => {
const [modulePath, mockDefs, globalDefs, opt = {}, err] = argsnormal(args)
const calleePath = (opt.parent || (err || new Error).stack.split('\n')[2])
.replace(/^.*file:\/\//, '') // rm every before filepath
.replace(/:[\d]*:[\d]*.*$/, '') // rm line and row number
.replace(/^.*:/, '') // rm windows-style drive location
Expand All @@ -44,19 +47,11 @@ const _esmock = async (argsObj, err) => {
return esmockModuleImportedSanitize(importedModule, modulePathKey)
}

const esmock = async (...args) => _esmock(argsToObj(args), new Error)

esmock.px = async (...args) => {
const argsObj = argsToObj(args)
argsObj.opt = { ...argsObj.opt, partial: true }
return _esmock(argsObj, new Error)
}
esmock.px = async (...args) => (
esmock(...argsnormal(args, [{ partial: true }, new Error])))

esmock.p = async (...args) => {
const argsObj = argsToObj(args)
argsObj.opt = { ...argsObj.opt, purge: false }
return _esmock(argsObj, new Error)
}
esmock.p = async (...args) => (
esmock(...argsnormal(args, [{ purge: false }, new Error])))

esmock.purge = mockModule => {
if (mockModule && /object|function/.test(typeof mockModule)
Expand Down
8 changes: 4 additions & 4 deletions src/esmockLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import urlDummy from './esmockDummy.js'

export default esmock

const [ major, minor ] = process.versions.node.split('.').map(it => +it)
const [major, minor] = process.versions.node.split('.').map(it => +it)
const isLT1612 = major < 16 || (major === 16 && minor < 12)

const esmockGlobalsAndAfterRe = /\?esmockGlobals=.*/
Expand Down Expand Up @@ -33,7 +33,7 @@ const nextResolveCall = async (nextResolve, specifier, context) => (

const resolve = async (specifier, context, nextResolve) => {
const { parentURL } = context
const [ esmockKeyParamSmall ] =
const [esmockKeyParamSmall] =
(parentURL && parentURL.match(/\?esmk=\d*/)) || []
const esmockKeyLong = esmockKeyParamSmall
? global.esmockKeyGet(esmockKeyParamSmall.split('=')[1])
Expand All @@ -42,8 +42,8 @@ const resolve = async (specifier, context, nextResolve) => {
if (!esmockKeyRe.test(esmockKeyLong))
return nextResolveCall(nextResolve, specifier, context)

const [ esmockKeyParam ] = String(esmockKeyLong).match(esmockKeyRe)
const [ keyUrl, keys ] = esmockKeyLong.split(esmockModuleKeysRe)
const [esmockKeyParam] = String(esmockKeyLong).match(esmockKeyRe)
const [keyUrl, keys] = esmockKeyLong.split(esmockModuleKeysRe)
const moduleGlobals = keyUrl && keyUrl.replace(esmockGlobalsAndBeforeRe, '')
// do not call 'nextResolve' for notfound modules
if (esmockKeyLong.includes(`notfound=${specifier}`)) {
Expand Down
2 changes: 1 addition & 1 deletion src/esmockModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const esmockModuleImportedSanitize = (importedModule, esmockKey) => {
const esmockModuleImportedPurge = modulePathKey => {
const purgeKey = key => key === 'null' || esmockCacheSet(key, null)
const longKey = esmockKeyGet(modulePathKey.split('esmk=')[1])
const [ url, keys ] = longKey.split('#-#esmockModuleKeys=')
const [url, keys] = longKey.split('#-#esmockModuleKeys=')

String(keys).split('#-#').forEach(purgeKey)
String(url.split('esmockGlobals=')[1]).split('#-#').forEach(purgeKey)
Expand Down
2 changes: 1 addition & 1 deletion tests/tests-ava/spec/esmock.ava.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ test('mocks inline `async import("name")`', async t => {
filePath: 'filePath'
}))

const [ , key ] = writeJSConfigFile.esmockKey.match(/esmk=(\d*)/)
const [, key] = writeJSConfigFile.esmockKey.match(/esmk=(\d*)/)
const keyRe = new RegExp(`esmockKey=${key}[^d]`)

const moduleKeys = Object.keys(esmock.esmockCache.mockDefs)
Expand Down
2 changes: 1 addition & 1 deletion tests/tests-node/esmock.node.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ test('mocks inline `async import("name")`', async () => {
filePath: 'filePath'
}))

const [ , key ] = writeJSConfigFile.esmockKey.match(/esmk=(\d*)/)
const [, key] = writeJSConfigFile.esmockKey.match(/esmk=(\d*)/)
const keyRe = new RegExp(`esmockKey=${key}[^d]`)

const moduleKeys = Object.keys(esmock.esmockCache.mockDefs)
Expand Down
13 changes: 13 additions & 0 deletions tests/tests-source-map/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,16 @@ test("using relative path", async (t) => {
const getHostname: typeof indexType.getHostname = indexModule.getHostname;
t.is(getHostname(), expectedHostname);
});

test("using opt.parent", async (t) => {
const indexModule = await esmock("../index.js", {
os: {
hostname: () => expectedHostname,
},
}, undefined, {
parent: import.meta.url
});

const getHostname: typeof indexType.getHostname = indexModule.getHostname;
t.is(getHostname(), expectedHostname);
});
2 changes: 1 addition & 1 deletion tests/tests-uvu/esmock.uvu.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ test('mocks inline `async import("name")`', async () => {
filePath: 'filePath'
}))

const [ , key ] = writeJSConfigFile.esmockKey.match(/esmk=(\d*)/)
const [, key] = writeJSConfigFile.esmockKey.match(/esmk=(\d*)/)
const keyRe = new RegExp(`esmockKey=${key}[^d]`)

const moduleKeys = Object.keys(esmock.esmockCache.mockDefs)
Expand Down