Skip to content
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
21 changes: 20 additions & 1 deletion packages/mocker/src/automocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,28 @@ export function mockObject(
continue
}

if (options.type === 'autospy' && type === 'Module') {
// Replace with clean object to recursively autospy exported module objects:
// export * as ns from "./ns"
// or
// import * as ns from "./ns"
// export { ns }
const exports = Object.create(null)
Object.defineProperty(exports, Symbol.toStringTag, {
value: 'Module',
configurable: true,
writable: true,
})
try {
newContainer[property] = exports
}
catch {
continue
}
}
// Sometimes this assignment fails for some unknown reason. If it does,
// just move along.
if (!define(newContainer, property, isFunction || options.type === 'autospy' ? value : {})) {
else if (!define(newContainer, property, isFunction || options.type === 'autospy' ? value : {})) {
continue
}

Expand Down
1 change: 1 addition & 0 deletions test/core/src/mocks/autospying-namespace/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * as NamespaceTarget from './namespaceTarget.js'
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const computeSquare = (n: number) => n * n
8 changes: 8 additions & 0 deletions test/core/test/mocking/autospying.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import axios from 'axios'
import { expect, test, vi } from 'vitest'
import { getAuthToken } from '../../src/env'
import * as NamespaceModule from '../../src/mocks/autospying-namespace/index.js'

vi.mock(import('../../src/env'), { spy: true })

vi.mock('axios', { spy: true })
vi.mock('../../src/mocks/autospying-namespace/index.js', { spy: true })

test('getAuthToken is spied', async () => {
import.meta.env.AUTH_TOKEN = '123'
Expand All @@ -23,3 +25,9 @@ test('package in __mocks__ has lower priority', async () => {
expect(axios.isAxiosError(new Error('test'))).toBe(false)
expect(axios.isAxiosError).toHaveBeenCalled()
})

test('spies on namespace re-exports', async () => {
expect(vi.isMockFunction(NamespaceModule.NamespaceTarget.computeSquare)).toBe(true)
expect(NamespaceModule.NamespaceTarget.computeSquare(5)).toBe(25)
expect(NamespaceModule.NamespaceTarget.computeSquare).toHaveBeenCalledTimes(1)
})
Loading