forked from vitest-dev/vitest
/
automocking.spec.ts
67 lines (52 loc) · 2.11 KB
/
automocking.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
import type * as exampleModule from '../src/example'
import log from '../src/log'
import { A } from '../src/moduleA'
import { methodSymbol, moduleWithSymbol } from '../src/moduleWithSymbol'
vi.mock('../src/log')
vi.mock('../src/moduleA')
vi.mock('../src/moduleWithSymbol')
test('all mocked are valid', async () => {
const example = await vi.importMock<typeof exampleModule>('../src/example')
// creates a new mocked function with no formal arguments.
expect(example.square.name).toEqual('square')
expect(example.square.length).toEqual(0)
// async functions get the same treatment as standard synchronous functions.
expect(example.asyncSquare.name).toEqual('asyncSquare')
expect(example.asyncSquare.length).toEqual(0)
// creates a new class with the same interface, member functions and properties are mocked.
expect(example.someClasses.constructor.name).toEqual('Bar')
expect(example.someClasses.foo.name).toEqual('foo')
expect(vi.isMockFunction(example.someClasses.foo)).toBe(true)
expect(example.someClasses.array.length).toEqual(0)
// creates a deeply cloned version of the original object.
expect(example.object).toEqual({
baz: 'foo',
bar: {
fiz: 1,
buzz: [],
},
})
// creates a new empty array, ignoring the original array.
expect(example.array.length).toEqual(0)
// creates a new property with the same primitive value as the original property.
expect(example.number).toEqual(123)
expect(example.string).toEqual('baz')
expect(example.boolean).toEqual(true)
expect(example.symbol).toEqual(Symbol.for('a.b.c'))
})
test('automock properly restores mock', async () => {
expect(log.warn()).toBeUndefined()
expect(moduleWithSymbol.warn()).toBeUndefined()
expect(moduleWithSymbol[methodSymbol]()).toBeUndefined()
expect(log.warn).toHaveProperty('mockImplementation')
vi.restoreAllMocks()
expect(() => {
log.warn()
}).not.toThrow()
expect(moduleWithSymbol[methodSymbol]()).toBe('hello')
expect(moduleWithSymbol.warn()).toBe('hello')
expect(log.warn).toHaveProperty('mockImplementation')
})
test('automock has a getter', () => {
expect(A).toBe('A')
})