/
vi.spec.ts
91 lines (74 loc) · 2.51 KB
/
vi.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* @vitest-environment jsdom
*/
import type { MockedFunction, MockedObject } from 'vitest'
import { describe, expect, test, vi } from 'vitest'
import { getWorkerState } from 'vitest/src/utils'
const expectType = <T>(obj: T) => obj
describe('testing vi utils', () => {
test('global scope has variable', () => {
const IntersectionObserverMock = vi.fn()
vi.stubGlobal('IntersectionObserver', IntersectionObserverMock)
expect(globalThis.IntersectionObserver).toBe(IntersectionObserverMock)
expect(window.IntersectionObserver).toBe(IntersectionObserverMock)
expect(IntersectionObserver).toBe(IntersectionObserverMock)
})
test('resetting modules', async () => {
const mod1 = await import('../src/env')
vi.resetModules()
const mod2 = await import('../src/env')
const mod3 = await import('../src/env')
expect(mod1).not.toBe(mod2)
expect(mod2).toBe(mod3)
})
test('resetting modules doesn\'t reset vitest', async () => {
const v1 = await import('vitest')
vi.resetModules()
const v2 = await import('vitest')
expect(v1).toBe(v2)
})
test('vi mocked', () => {
expectType<MockedObject<{ bar: () => boolean }>>({
bar: vi.fn(() => true),
})
expectType<MockedFunction<() => boolean>>(vi.fn(() => true))
expectType<MockedFunction<() => boolean>>(vi.fn())
})
test('vi partial mocked', () => {
interface FooBar {
foo: () => void
bar: () => boolean
baz: string
}
type FooBarFactory = () => FooBar
const mockFactory: FooBarFactory = vi.fn()
vi.mocked(mockFactory, { partial: true }).mockReturnValue({
foo: vi.fn(),
})
vi.mocked(mockFactory, { partial: true, deep: false }).mockReturnValue({
bar: vi.fn(),
})
vi.mocked(mockFactory, { partial: true, deep: true }).mockReturnValue({
baz: 'baz',
})
})
test('can change config', () => {
const state = getWorkerState()
expect(state.config.hookTimeout).toBe(10000)
expect(state.config.clearMocks).toBe(false)
vi.setConfig({ hookTimeout: 6000, clearMocks: true })
expect(state.config.hookTimeout).toBe(6000)
expect(state.config.clearMocks).toBe(true)
vi.resetConfig()
expect(state.config.hookTimeout).toBe(10000)
expect(state.config.clearMocks).toBe(false)
})
test('loads unloaded module', async () => {
let mod: any
import('../src/timeout').then(m => mod = m)
expect(mod).toBeUndefined()
await vi.dynamicImportSettled()
expect(mod).toBeDefined()
expect(mod.timeout).toBe(100)
})
})