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

add import json tests #247

Merged
merged 8 commits into from
Nov 4, 2023
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
@@ -1,6 +1,6 @@
{
"plugins": [],
"ignorePatterns": ["dist"],
"ignorePatterns": ["importsJSONfile.js"],
"extends": [
"eslint:recommended",
"plugin:markdown/recommended"
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

* 2.5.9 _Nov.11.2023_
* [mock Array-type default export,](https://github.com/iambumblehead/esmock/pull/266) thanks @altearius
* [support json import mocking,](https://github.com/iambumblehead/esmock/pull/247) only working at node v21, see [node#49724](https://github.com/nodejs/node/issues/49724)
* 2.5.8 _Oct.23.2023_
* [catch yarn PnP exceptions](https://github.com/iambumblehead/esmock/pull/262) @koshic
* 2.5.7 _Oct.20.2023_
Expand Down
12 changes: 11 additions & 1 deletion src/esmockCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ const esmockCache = {
mockDefs: {}
}

const esmockModuleIdSourceSet = (keysource, source) => (
esmockPostMessage({ keysource, source }),
global.mockKeysSource[String(keysource)] = source)

const esmockModuleIdSourceGet = keysource => (
global.mockKeysSource[String(keysource)])

const esmockTreeIdSet = (key, keylong) => (
esmockPostMessage({ key, keylong }),
global.mockKeys[String(key)] = keylong)
Expand All @@ -31,7 +38,8 @@ Object.assign(global, {
esmockCache,
esmockCacheGet,
esmockTreeIdGet,
mockKeys: global.mockKeys || {}
mockKeys: global.mockKeys || {},
mockKeysSource: global.mockKeysSource || {}
})

export {
Expand All @@ -40,6 +48,8 @@ export {
esmockCacheGet,
esmockTreeIdSet,
esmockTreeIdGet,
esmockModuleIdSourceSet,
esmockModuleIdSourceGet,
esmockCacheResolvedPathIsESMGet,
esmockCacheResolvedPathIsESMSet
}
19 changes: 17 additions & 2 deletions src/esmockLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,14 @@ const moduleIdReCreate = (moduleid, treeid) => new RegExp(

// node v12.0-v18.x, global
const mockKeys = global.mockKeys = (global.mockKeys || {})
const mockKeysSource = global.mockKeysSource = (global.mockKeysSource || {})

// node v20.0-v20.6
const globalPreload = !module.register && (({ port }) => (
port.addEventListener('message', ev => (
mockKeys[ev.data.key] = ev.data.keylong)),
ev.data.keysource
? mockKeysSource[ev.data.keysource] = ev.data.source
: mockKeys[ev.data.key] = ev.data.keylong)),
port.unref(),
'global.postMessageEsmk = d => port.postMessage(d)'
))
Expand All @@ -44,7 +47,9 @@ const globalPreload = !module.register && (({ port }) => (
const initialize = module.register && (data => {
if (data && data.port) {
data.port.on('message', msg => {
mockKeys[msg.key] = msg.keylong
msg.keysource
? mockKeysSource[msg.keysource] = msg.source
: mockKeys[msg.key] = msg.keylong
})
}
})
Expand Down Expand Up @@ -198,6 +203,16 @@ const load = async (url, context, nextLoad) => {
.split(',')

if (exportedNames && exportedNames[0]) {
if (mockKeysSource[url]) {
return {
// ...await nextLoad(url, context),
format: 'json',
shortCircuit: true,
responseURL: encodeURI(url),
source: mockKeysSource[url]
}
}

return {
format: 'module',
shortCircuit: true,
Expand Down
15 changes: 13 additions & 2 deletions src/esmockModule.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from 'fs'
import url from 'url'
import resolvewith from 'resolvewithplus'
import esmockErr from './esmockErr.js'
import esmockIsESMRe from './esmockIsESMRe.js'
Expand All @@ -7,6 +8,7 @@ import {
esmockTreeIdSet,
esmockTreeIdGet,
esmockCacheSet,
esmockModuleIdSourceSet,
esmockCacheResolvedPathIsESMGet,
esmockCacheResolvedPathIsESMSet
} from './esmockCache.js'
Expand All @@ -18,6 +20,7 @@ const nextId = ((id = 0) => () => ++id)()
const objProto = Object.getPrototypeOf({})
const isPlainObj = o => Object.getPrototypeOf(o) === objProto
const iscoremodule = resolvewith.iscoremodule
const isJSONExtnRe = /\.json$/i

// assigning the object to its own prototypal inheritor can error, eg
// 'Cannot assign to read only property \'F_OK\' of object \'#<Object>\''
Expand All @@ -36,7 +39,7 @@ const esmockModuleMergeDefault = (defLive, def) =>

const esmockModuleApply = (defLive, def, fileURL) => {
// no fileURL here indicates 'import' mock, 'default' not needed
if (fileURL === null)
if (fileURL === null || isJSONExtnRe.test(fileURL))
return Object.assign({}, defLive || {}, def)

if (Array.isArray(def))
Expand Down Expand Up @@ -95,9 +98,13 @@ const esmockModuleImportedPurge = treeid => {
String(url.split('esmkgdefs=')[1]).split('#-#').forEach(purgeKey)
}

const esmockImport = async fileURL => isJSONExtnRe.test(fileURL)
? JSON.parse(fs.readFileSync(new url.URL(fileURL), 'utf-8'))
: import(fileURL)

const esmockModuleCreate = async (treeid, def, id, fileURL, opt) => {
def = esmockModuleApply(
opt.strict || !fileURL || await import(fileURL), def, fileURL)
opt.strict || !fileURL || await esmockImport(fileURL), def, fileURL)

const mockModuleKey = (fileURL || 'file:///' + id) + '?' + [
'esmkTreeId=' + treeid,
Expand All @@ -107,6 +114,10 @@ const esmockModuleCreate = async (treeid, def, id, fileURL, opt) => {
'exportNames=' + Object.keys(def).sort().join()
].join('&')

if (isJSONExtnRe.test(fileURL)) {
esmockModuleIdSourceSet(mockModuleKey, JSON.stringify(def))
}

esmockCacheSet(mockModuleKey, def)

return mockModuleKey
Expand Down
1 change: 1 addition & 0 deletions tests/local/example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "example": "json" }
5 changes: 5 additions & 0 deletions tests/local/importsJSONfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import JSONobj from './example.json' assert { type: 'json' };

export {
JSONobj
}
33 changes: 33 additions & 0 deletions tests/tests-node/esmock.node.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -548,3 +548,36 @@ test('should mock an exported array', async () => {

assert.deepStrictEqual(importsArray(), ['mocked'])
})

test('should mock imported json', async () => {
const importsJSON = await esmock(
'../local/importsJSONfile.js', {
'../local/example.json': {
'test-example': 'test-json-a'
}
})

if (/^(18|20)$/.test(process.versions.node.split('.')[0]))
return assert.ok(true)

assert.strictEqual(
Object.keys(importsJSON.JSONobj).sort().join(), 'example,test-example')
assert.strictEqual(importsJSON.JSONobj['test-example'], 'test-json-a')
assert.strictEqual(importsJSON.JSONobj['example'], 'json')
})

test('should mock imported json (strict)', async () => {
const importsJSON = await esmock.strict(
'../local/importsJSONfile.js', {
'../local/example.json': {
'test-example': 'test-json-b'
}
})

if (/^(18|20)$/.test(process.versions.node.split('.')[0]))
return assert.ok(true)

assert.strictEqual(
Object.keys(importsJSON.JSONobj).sort().join(), 'test-example')
assert.strictEqual(importsJSON.JSONobj['test-example'], 'test-json-b')
})