Skip to content

Commit

Permalink
fix(cli): mock document.execCommand when emulating browser env (#7062)
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Jul 8, 2024
1 parent 60ad7e7 commit e54ae8a
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions packages/sanity/src/_internal/cli/util/mockBrowserEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,31 @@ const getFakeGlobals = (basePath: string) => ({
})),
})

const getFakeDocumentProps = () => ({
execCommand: function execCommand(
// Provide the right arity for the function, even if unused
/* eslint-disable @typescript-eslint/no-unused-vars, unused-imports/no-unused-vars */
_commandName: string,
_showDefaultUI: boolean,
_valueArgument: unknown,
/* eslint-enable @typescript-eslint/no-unused-vars, unused-imports/no-unused-vars */
) {
// Return false to indicate "unsupported"
return false
},
})

function provideFakeGlobals(basePath: string): () => void {
const globalEnv = global as any as Record<string, unknown>
const globalWindow = global.window as Record<string, any>
const globalDocument = (global.document || document || {}) as Record<string, any>

const fakeGlobals = getFakeGlobals(basePath)
const fakeDocumentProps = getFakeDocumentProps()

const stubbedGlobalKeys: string[] = []
const stubbedWindowKeys: string[] = []
const stubbedDocumentKeys: string[] = []

for (const [rawKey, value] of Object.entries(fakeGlobals)) {
if (typeof value === 'undefined') {
Expand All @@ -98,6 +116,18 @@ function provideFakeGlobals(basePath: string): () => void {
}
}

for (const [rawKey, value] of Object.entries(fakeDocumentProps)) {
if (typeof value === 'undefined') {
continue
}

const key = rawKey as keyof typeof fakeDocumentProps
if (!(key in globalDocument)) {
globalDocument[key] = fakeDocumentProps[key]
stubbedDocumentKeys.push(key)
}
}

return () => {
stubbedGlobalKeys.forEach((key) => {
delete globalEnv[key]
Expand All @@ -106,6 +136,10 @@ function provideFakeGlobals(basePath: string): () => void {
stubbedWindowKeys.forEach((key) => {
delete globalWindow[key]
})

stubbedDocumentKeys.forEach((key) => {
delete globalDocument[key]
})
}
}

Expand Down

0 comments on commit e54ae8a

Please sign in to comment.