Skip to content

Commit

Permalink
fix: allow referring to first seen value while automocking (#1879)
Browse files Browse the repository at this point in the history
  • Loading branch information
simon-abbott authored Aug 19, 2022
1 parent 637e2b3 commit 285ac7c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/vitest/src/runtime/mocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ export class VitestMocker {
// Special handling of references we've seen before to prevent infinite
// recursion in circular objects.
const refId = refs.getId(value)
if (refId) {
if (refId !== undefined) {
finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)))
continue
}
Expand Down
4 changes: 4 additions & 0 deletions test/core/src/mockedD.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { MockedC } from './mockedC'

export default MockedC
export * from './mockedC'
14 changes: 14 additions & 0 deletions test/core/test/mocked.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import { two } from '../src/submodule'
import * as mocked from '../src/mockedA'
import { mockedB } from '../src/mockedB'
import { MockedC, asyncFunc, exportedStream } from '../src/mockedC'
import MockedDefault, { MockedC as MockedD } from '../src/mockedD'
import * as globalMock from '../src/global-mock'

vitest.mock('../src/submodule')
vitest.mock('virtual-module', () => ({ value: 'mock' }))
vitest.mock('../src/mockedC')
vitest.mock('../src/mockedD')

test('submodule is mocked to return "two" as 3', () => {
assert.equal(3, two)
Expand Down Expand Up @@ -37,6 +39,7 @@ describe('mocked classes', () => {
test('should not delete the prototype', () => {
expect(MockedC).toBeTypeOf('function')
expect(MockedC.prototype.doSomething).toBeTypeOf('function')
expect(MockedC.prototype.constructor).toBe(MockedC)
})

test('should mock the constructor', () => {
Expand All @@ -57,6 +60,17 @@ describe('mocked classes', () => {
})
})

describe('default exported classes', () => {
test('should preserve equality for re-exports', () => {
expect(MockedDefault).toEqual(MockedD)
})

test('should preserve prototype', () => {
expect(MockedDefault.prototype.constructor).toBe(MockedDefault)
expect(MockedD.prototype.constructor).toBe(MockedD)
})
})

test('async functions should be mocked', () => {
expect(asyncFunc()).toBeUndefined()
expect(vi.mocked(asyncFunc).mockResolvedValue).toBeDefined()
Expand Down

0 comments on commit 285ac7c

Please sign in to comment.