/
fn.test.ts
94 lines (66 loc) · 1.74 KB
/
fn.test.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
92
93
94
import { assert, describe, expect, it, vitest } from 'vitest'
describe('mock', () => {
it('basic', () => {
const fn = vitest.fn()
expect(fn).not.toHaveBeenCalled()
fn()
expect(fn).toHaveBeenCalled()
expect(fn).toHaveBeenCalledOnce()
expect(fn).toHaveBeenCalledTimes(1)
fn.mockReset()
expect(fn).not.toHaveBeenCalled()
fn('World', 2)
fn('Hi', 1)
expect(fn.mock.calls[1]).toEqual(['Hi', 1])
expect(fn).toHaveBeenNthCalledWith(1, 'World', 2)
expect(fn).toHaveBeenNthCalledWith(2, 'Hi', 1)
expect(fn).toHaveBeenLastCalledWith('Hi', 1)
expect(fn).toHaveBeenCalledWith('Hi', 1)
})
it('toHaveBeenCalledWith', () => {
const fn = vitest.fn()
fn('Hi', 2)
expect(fn).toHaveBeenCalledWith('Hi', 2)
})
it('returns', () => {
let i = 0
const fn = vitest.fn(() => String(++i))
expect(fn).not.toHaveReturned()
fn()
expect(fn).toHaveReturned()
expect(fn).toHaveReturnedTimes(1)
expect(fn).toHaveReturnedWith('1')
fn()
fn()
expect(fn).toHaveReturnedTimes(3)
expect(fn).toHaveNthReturnedWith(2, '2')
expect(fn).toHaveLastReturnedWith('3')
})
it('throws', () => {
let i = 0
const fn = vitest.fn(() => {
if (i === 0) {
++i
throw new Error('error')
}
return String(++i)
})
try {
fn()
}
catch {}
expect(fn).not.toHaveReturned()
fn()
expect(fn).toHaveReturned()
fn()
try {
expect(fn).toHaveNthReturnedWith(1, '1')
assert.fail('expect should throw, since 1st call is thrown')
}
catch {}
// not throws
expect(fn).not.toHaveNthReturnedWith(1, '1')
expect(fn).toHaveReturnedTimes(2)
expect(fn).toHaveNthReturnedWith(3, '3')
})
})