/
factory.test.ts
87 lines (74 loc) · 2.63 KB
/
factory.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
import axios from 'axios'
import * as example from '../src/example'
import * as moduleA from '../src/moduleA'
import logger from '../src/log'
vi
.mock('../src/example', () => ({
mocked: true,
then: 'a then export',
ok: undefined,
square: (a: any, b: any) => a + b,
asyncSquare: async (a: any, b: any) => Promise.resolve(a + b),
}))
// doesn't think comments are mocks
// vi.mock('../src/example', () => ({
// mocked: false,
// }))
vi.mock('../src/moduleA', async () => {
const actual = await vi.importActual<any>('../src/moduleA')
return {
B: 'B',
...actual,
}
})
vi.mock('axios', () => {
return {
default: {
get: vi.fn(),
},
}
})
vi.mock('../src/log.ts', async () => {
// can import the same module inside and does not go into an infinite loop
const log = await import('../src/log')
return {
default: {
...log.default,
info: vi.fn(),
},
}
})
vi.mock('../src/default.ts', () => null)
describe('mocking with factory', () => {
test('missing exports on mock', () => {
expect(() => example.default).toThrowError('[vitest] No "default" export is defined on the "../src/example" mock')
expect(() => example.boolean).toThrowError('[vitest] No "boolean" export is defined on the "../src/example" mock')
expect(() => example.object).toThrowError('[vitest] No "object" export is defined on the "../src/example" mock')
expect(() => example.array).toThrowError('[vitest] No "array" export is defined on the "../src/example" mock')
expect(() => example.someClasses).toThrowError('[vitest] No "someClasses" export is defined on the "../src/example" mock')
})
it('non-object return on factory gives error', async () => {
await expect(() => import('../src/default').then(m => m.default)).rejects
.toThrowError('[vitest] vi.mock("../src/default.ts", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?')
})
test('defined exports on mock', async () => {
expect((example as any).ok).toBe(undefined)
expect((example as any).then).toBe('a then export')
expect((example as any).mocked).toBe(true)
expect(example.square(2, 3)).toBe(5)
expect(example.asyncSquare(2, 3)).resolves.toBe(5)
})
test('successfully with actual', () => {
expect(moduleA.A).toBe('A')
expect((moduleA as any).B).toBe('B')
})
test('mocks node_modules', () => {
axios.get('./path')
expect(axios.get).toHaveBeenCalledTimes(1)
})
test('logger extended', () => {
expect(logger.warn).toBeTypeOf('function')
// @ts-expect-error extending module
expect(logger.info).toBeTypeOf('function')
})
})