Navigation Menu

Skip to content

Commit

Permalink
fix: correctly automock nested interoped defaults (#2559)
Browse files Browse the repository at this point in the history
* fix: correctly automock nested interoped defaults

* chore: cleanup

* chore: cleanup
  • Loading branch information
sheremet-va committed Dec 25, 2022
1 parent a35ac70 commit a431df8
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 2 deletions.
4 changes: 4 additions & 0 deletions examples/mocks/src/external/cjs-pseudoesm.cjs
@@ -0,0 +1,4 @@
const fn = () => {}

exports.fn = fn
Object.defineProperty(exports, '__esModule', { value: true, enumerable: false })
1 change: 1 addition & 0 deletions examples/mocks/src/external/default-cjs.cjs
@@ -0,0 +1 @@
module.exports = require('./cjs-pseudoesm.cjs')
File renamed without changes.
2 changes: 1 addition & 1 deletion examples/mocks/test/external.test.ts
@@ -1,4 +1,4 @@
import '../src/external.mjs'
import '../src/external/external.mjs'
import { expect, test, vi } from 'vitest'
import axios from 'axios'

Expand Down
9 changes: 9 additions & 0 deletions examples/mocks/test/nested-default.spec.ts
@@ -0,0 +1,9 @@
// @vitest-environment jsdom

import * as modDefaultCjs from '../src/external/default-cjs.cjs'

vi.mock('../src/external/default-cjs.cjs')

test('default is mocked', () => {
expect(vi.isMockFunction(modDefaultCjs.default.fn)).toBe(true)
})
2 changes: 1 addition & 1 deletion examples/mocks/vite.config.ts
Expand Up @@ -24,7 +24,7 @@ export default defineConfig({
globals: true,
environment: 'node',
deps: {
external: [/src\/external\.mjs/],
external: [/src\/external/],
},
},
})
20 changes: 20 additions & 0 deletions packages/vite-node/src/client.ts
Expand Up @@ -414,6 +414,26 @@ export class ViteNodeRunner {
return defaultExport !== undefined
return prop in mod || (defaultExport && prop in defaultExport)
},
// this is needed for mocker to know what is available to mock
ownKeys(mod) {
const keys = Reflect.ownKeys(mod)
if (!defaultExport || isPrimitive(defaultExport))
return keys
const allKeys = [...keys, 'default', ...Reflect.ownKeys(defaultExport)]
return Array.from(new Set(allKeys))
},
getOwnPropertyDescriptor(mod, prop) {
const descriptor = Reflect.getOwnPropertyDescriptor(mod, prop)
if (descriptor)
return descriptor
if (prop === 'default' && defaultExport !== undefined) {
return {
value: defaultExport,
enumerable: true,
configurable: true,
}
}
},
})
}
}
Expand Down

0 comments on commit a431df8

Please sign in to comment.