Skip to content

Commit

Permalink
Merge pull request #144 from iambumblehead/re-143-small-changes
Browse files Browse the repository at this point in the history
Re 143 small changes
  • Loading branch information
iambumblehead authored Sep 8, 2022
2 parents 302ca82 + b957435 commit de37f76
Show file tree
Hide file tree
Showing 9 changed files with 39 additions and 49 deletions.
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
},
"jest": {
"runner": "jest-light-runner"
},
}
}
```

Expand Down Expand Up @@ -70,12 +70,10 @@ test('should mock packages and local files', async () => {

test('should do global instance mocks —third param', async () => {
const { getFile } = await esmock('../src/main.js', {}, {
fs: {
readFileSync: () => 'returns this globally'
}
fs: { readFileSync: () => 'returns this 🌎 globally' }
})

assert.strictEqual(getFile(), 'returns this globally')
assert.strictEqual(getFile(), 'returns this 🌎 globally')
})

test('should mock "await import()" using esmock.p', async () => {
Expand All @@ -95,7 +93,7 @@ test('should support "strict" mocking, at esmock.strict', async () => {
path: { dirname: () => '/path/to/file' }
})

// error, because the "path" mock above does not define path.basename
// error, because "path" mock above does not define path.basename
await assert.rejects(async () => pathWrapper.basename('/dog.png'), {
name: 'TypeError',
message: 'path.basename is not a function'
Expand Down
5 changes: 1 addition & 4 deletions src/esmock.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import esmockIsLoader from './esmockIsLoader.js'
import esmockCache from './esmockCache.js'
import esmockArgs from './esmockArgs.js'

import {
Expand All @@ -7,10 +8,6 @@ import {
esmockModuleImportedSanitize
} from './esmockModule.js'

import {
esmockCache
} from './esmockCache.js'

const esmock = async (...args) => {
const [modulePath, mockDefs, globalDefs, opt = {}, err] = esmockArgs(args)
const calleePath = (opt.parent || (err || new Error).stack.split('\n')[2])
Expand Down
2 changes: 1 addition & 1 deletion src/esmockCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Object.assign(global, {
})

export {
esmockCache,
esmockCache as default,
esmockCacheSet,
esmockCacheGet,
esmockKeySet,
Expand Down
12 changes: 4 additions & 8 deletions src/esmockLoader.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import process from 'process'
export * from './esmock.js'
export {default} from './esmock.js'
import urlDummy from './esmockDummy.js'

const [major, minor] = process.versions.node.split('.').map(it => +it)
Expand Down Expand Up @@ -89,7 +87,7 @@ const load = async (url, context, nextLoad) => {
if (url.startsWith(urlDummy)) {
url = url.replace(withHashRe, '')
if (notfoundRe.test(url))
url = url.replace(urlDummy, `file:///${(url.match(notfoundRe) || [])[1]}`)
url = url.replace(urlDummy, `file:///${url.match(notfoundRe)[1]}`)
}

const exportedNames = exportNamesRe.test(url) &&
Expand All @@ -112,8 +110,6 @@ const load = async (url, context, nextLoad) => {
// node lt 16.12 require getSource, node gte 16.12 warn remove getSource
const getSource = isLT1612 && load

export {
load,
resolve,
getSource
}
export * from './esmock.js'
export {default} from './esmock.js'
export {load, resolve, getSource}
41 changes: 20 additions & 21 deletions src/esmockModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,13 @@ const esmockModuleIsESM = (mockPathFull, isesm) => {
const esmockModuleImportedSanitize = (importedModule, esmockKey) => {
const importedDefault = 'default' in importedModule && importedModule.default

if (!/boolean|string|number/.test(typeof importedDefault)) {
// an example of [object Module]: import * as mod from 'fs'; export mod;
return Object.prototype.toString.call(importedDefault) === '[object Module]'
? Object.assign({}, importedDefault, importedModule, { esmockKey })
: Object.assign(importedDefault, importedModule, { esmockKey })
}

return importedModule
if (/boolean|string|number/.test(typeof importedDefault))
return importedModule

// an example of [object Module]: import * as mod from 'fs'; export mod;
return Object.isExtensible(importedDefault)
? Object.assign(importedDefault, importedModule, { esmockKey })
: Object.assign({}, importedDefault, importedModule, { esmockKey })
}

const esmockModuleImportedPurge = modulePathKey => {
Expand Down Expand Up @@ -118,54 +117,54 @@ const esmockModuleCreate = async (esmockKey, key, mockPathFull, mockDef, opt) =>
}

// eslint-disable-next-line max-len
const esmockModulesCreate = async (pathCallee, pathModule, esmockKey, defs, keys, mocks, opt) => {
const esmockModulesCreate = async (parent, moduleFileURL, esmockKey, defs, keys, mocks, opt) => {
keys = keys || Object.keys(defs)
mocks = mocks || []

if (!keys.length)
return mocks

let mockedPathFull = resolvewith(keys[0], pathCallee)
let mockedPathFull = resolvewith(keys[0], parent)
if (!mockedPathFull && opt.isModuleNotFoundError === false) {
mockedPathFull = 'file:///' + keys[0]
opt = Object.assign({ isfound: false }, opt)
}

if (!mockedPathFull) {
pathCallee = pathCallee
parent = parent
.replace(/^\/\//, '')
.replace(process.cwd(), '.')
.replace(process.env.HOME, '~')
throw new Error(`not a valid path: "${keys[0]}" (used by ${pathCallee})`)
throw new Error(`invalid moduleId: "${keys[0]}" (used by ${parent})`)
}

mocks.push(await esmockModuleCreate(
esmockKey, keys[0], mockedPathFull, defs[keys[0]], opt))

return esmockModulesCreate(
pathCallee, pathModule, esmockKey, defs, keys.slice(1), mocks, opt)
parent, moduleFileURL, esmockKey, defs, keys.slice(1), mocks, opt)
}

const esmockModuleMock = async (calleePath, modulePath, defs, gdefs, opt) => {
const pathModuleFull = resolvewith(modulePath, calleePath)
const esmockModuleMock = async (parent, moduleId, defs, gdefs, opt) => {
const moduleFileURL = resolvewith(moduleId, parent)
const esmockKey = typeof opt.key === 'number' ? opt.key : esmockNextKey()
const esmockModuleKeys = await esmockModulesCreate(
calleePath, pathModuleFull, esmockKey, defs, Object.keys(defs), 0, opt)
parent, moduleFileURL, esmockKey, defs, Object.keys(defs), 0, opt)
const esmockGlobalKeys = await esmockModulesCreate(
calleePath, pathModuleFull, esmockKey, gdefs, Object.keys(gdefs), 0, opt)
parent, moduleFileURL, esmockKey, gdefs, Object.keys(gdefs), 0, opt)

if (pathModuleFull === null)
throw new Error(`modulePath not found: "${modulePath}"`)
if (moduleFileURL === null)
throw new Error(`invalid moduleId: "${moduleId}"`)

const esmockKeyLong = pathModuleFull + '?' +
const esmockKeyLong = moduleFileURL + '?' +
'key=:esmockKey?esmockGlobals=:esmockGlobals#-#esmockModuleKeys=:moduleKeys'
.replace(/:esmockKey/, esmockKey)
.replace(/:esmockGlobals/, esmockGlobalKeys.join('#-#') || 'null')
.replace(/:moduleKeys/, esmockModuleKeys.join('#-#'))

esmockKeySet(String(esmockKey), esmockKeyLong)

return pathModuleFull + `?esmk=${esmockKey}`
return moduleFileURL + `?esmk=${esmockKey}`
}

export {
Expand Down
4 changes: 2 additions & 2 deletions tests/tests-ava/spec/esmock.ava.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ test('should throw error if local file not found', async t => {
})

t.true(err.message.startsWith(
'modulePath not found: "../../local/not/found.js"'))
'invalid moduleId: "../../local/not/found.js"'))
})

test('should throw error if local definition file not found', async t => {
Expand All @@ -78,7 +78,7 @@ test('should throw error if local definition file not found', async t => {
})

t.true(err.message.startsWith(
'not a valid path: "../../local/not/found.js"'))
'invalid moduleId: "../../local/not/found.js"'))
})

test('should mock a module', async t => {
Expand Down
2 changes: 1 addition & 1 deletion tests/tests-jest/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"type": "module",
"description": "esmock unit tests, tsm with node native runner",
"description": "esmock unit tests, jest with jest-light-runner",
"repository": {
"type": "git",
"url": "https://github.com/iambumblehead/esmock.git"
Expand Down
8 changes: 4 additions & 4 deletions tests/tests-node/esmock.node.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ test('should throw error if local file not found', async () => {
createString: () => 'test string'
}
}), {
message: 'modulePath not found: "../local/not/found.js"'
message: 'invalid moduleId: "../local/not/found.js"'
})
})

Expand All @@ -86,7 +86,7 @@ test('should throw error if local definition file not found', async () => {
createString: () => 'test string'
}
}), {
message: /not a valid path: "..\/local\/not\/found.js" \(used by/
message: /invalid moduleId: "..\/local\/not\/found.js" \(used by/
})
})

Expand Down Expand Up @@ -393,7 +393,7 @@ test('should not error when mocked file has space in path', async () => {
assert.strictEqual(main.wild, 'tamed')
})

test('should strict mock by default, partial mock optional', async () => {
test('should partial mock by default, strict mock optional', async () => {
const wildfile = await import('../local/space in path/wild-file.js')
const mainstrict = await esmock.strict('../local/main.js', {
'../local/space in path/wild-file.js': {
Expand All @@ -418,7 +418,7 @@ test('should strict mock by default, partial mock optional', async () => {
true, wildfilenamedexports.every(e => mainpartialwildexports.includes(e)))
})

test('should strict mock by default, partial mock optional', async () => {
test('should throw error when strict mock definition not found', async () => {
const pathWrapStrict = await esmock.strict('../local/pathWrap.js', {
path: { dirname: '/path/to/file' }
})
Expand Down
4 changes: 2 additions & 2 deletions tests/tests-uvu/esmock.uvu.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ test('should throw error if local file not found', async () => {
}
})
} catch (e) {
assert.is(e.message, 'modulePath not found: "../local/not/found.js"')
assert.is(e.message, 'invalid moduleId: "../local/not/found.js"')
}
})

Expand All @@ -45,7 +45,7 @@ test('should throw error if local definition file not found', async () => {
})
} catch (e) {
assert.ok(e.message.startsWith(
'not a valid path: "../local/not/found.js" (used by'))
'invalid moduleId: "../local/not/found.js" (used by'))
}
})

Expand Down

0 comments on commit de37f76

Please sign in to comment.