Skip to content

Commit

Permalink
fix: Reflect.get called on non-object
Browse files Browse the repository at this point in the history
closes #479
  • Loading branch information
sheremet-va committed Jan 8, 2022
1 parent 23e1e62 commit 3c9073a
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 7 deletions.
16 changes: 9 additions & 7 deletions packages/vitest/src/node/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ function hasNestedDefault(target: any) {
return '__esModule' in target && target.__esModule && 'default' in target.default
}

function proxyMethod(name: 'get' | 'set' | 'has' | 'deleteProperty', isNested: boolean) {
function proxyMethod(name: 'get' | 'set' | 'has' | 'deleteProperty', tryDefault: boolean) {
return function(target: any, key: string | symbol, ...args: [any?, any?]) {
const result = Reflect[name](target, key, ...args)
if ((isNested && key === 'default') || !result)
if(typeof target.default !== 'object')
return result
if ((tryDefault && key === 'default') || typeof result === 'undefined')
return Reflect[name](target.default, key, ...args)
return result
}
Expand All @@ -46,12 +48,12 @@ export async function interpretedImport(path: string, interpretDefault: boolean)
const mod = await import(path)

if (interpretDefault && 'default' in mod) {
const isNested = hasNestedDefault(mod)
const tryDefault = hasNestedDefault(mod)
return new Proxy(mod, {
get: proxyMethod('get', isNested),
set: proxyMethod('set', isNested),
has: proxyMethod('has', isNested),
deleteProperty: proxyMethod('deleteProperty', isNested),
get: proxyMethod('get', tryDefault),
set: proxyMethod('set', tryDefault),
has: proxyMethod('has', tryDefault),
deleteProperty: proxyMethod('deleteProperty', tryDefault),
})
}

Expand Down
1 change: 1 addition & 0 deletions test/cjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"givens": "1.3.9",
"history": "^5.2.0",
"prettier": "^2.5.1",
"temp-dir": "^2.0.0",
"vitest": "workspace:*"
}
}
5 changes: 5 additions & 0 deletions test/cjs/test/interpret-default.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { expect, it } from 'vitest'
import { format } from 'prettier'
import givens from 'givens'
import tempDir from 'temp-dir'

it('prettier', () => {
expect(format('const a : A = \'t\'', { parser: 'typescript' }).trim())
Expand All @@ -11,3 +12,7 @@ it('has nested default', () => {
expect(typeof givens).toBe('function')
expect(givens.name).toBe('getGiven')
})

it('nested default is not an object', () => {
expect(typeof tempDir).toBe('string')
})
5 changes: 5 additions & 0 deletions test/cjs/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"compilerOptions": {
"esModuleInterop": true
}
}

0 comments on commit 3c9073a

Please sign in to comment.