Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow referring to first seen value while automocking #1879

Merged
merged 1 commit into from Aug 19, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/vitest/src/runtime/mocker.ts
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
@@ -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
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