-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjest.setup.js
More file actions
222 lines (204 loc) · 6.08 KB
/
Copy pathjest.setup.js
File metadata and controls
222 lines (204 loc) · 6.08 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import '@testing-library/jest-dom'
import { ReadableStream, TransformStream, WritableStream } from 'stream/web'
import { TextEncoder, TextDecoder } from 'util'
// Polyfill for Web Streams API
global.ReadableStream = ReadableStream
global.TransformStream = TransformStream
global.WritableStream = WritableStream
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
// Mock Next.js router
jest.mock('next/navigation', () => ({
useRouter() {
return {
push: jest.fn(),
replace: jest.fn(),
prefetch: jest.fn(),
back: jest.fn(),
forward: jest.fn(),
refresh: jest.fn(),
}
},
useSearchParams() {
return new URLSearchParams()
},
usePathname() {
return '/'
},
}))
// Mock localStorage
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
clear: jest.fn(),
}
global.localStorage = localStorageMock
// Mock IndexedDB
const indexedDBMock = {
open: jest.fn().mockImplementation(() => {
return Promise.resolve({
transaction: jest.fn().mockReturnValue({
objectStore: jest.fn().mockReturnValue({
add: jest.fn(),
put: jest.fn(),
get: jest.fn(),
delete: jest.fn(),
getAll: jest.fn().mockResolvedValue([])
})
}),
createObjectStore: jest.fn(),
close: jest.fn()
})
}),
deleteDatabase: jest.fn(),
}
global.indexedDB = indexedDBMock
// 增强 File API Mock
global.File = class File {
constructor(fileBits, fileName, options) {
this.name = fileName
this.size = fileBits.length
this.type = options?.type || ''
this.lastModified = Date.now()
}
}
// 增强 FileReader Mock
global.FileReader = class FileReader {
constructor() {
this.readyState = 0
this.result = null
this.error = null
this.onload = null
this.onerror = null
this.onabort = null
}
readAsText(file) {
setTimeout(() => {
this.readyState = 2
// 根据文件类型返回不同内容
if (file.name.endsWith('.md')) {
this.result = '# Mock Markdown Content\\n\\nThis is a mock markdown file for testing.'
} else if (file.name.endsWith('.json')) {
this.result = '{"title": "Mock JSON", "content": "test data"}'
} else {
this.result = 'Mock file content for testing purposes.'
}
if (this.onload) this.onload({ target: this })
}, 0)
}
readAsArrayBuffer() {
setTimeout(() => {
this.readyState = 2
// 模拟不同文件类型的ArrayBuffer
const mockData = new Uint8Array([0x50, 0x4B, 0x03, 0x04]) // ZIP header for DOCX
this.result = mockData.buffer
if (this.onload) this.onload({ target: this })
}, 0)
}
readAsDataURL(file) {
setTimeout(() => {
this.readyState = 2
if (file.type === 'application/pdf') {
this.result = 'data:application/pdf;base64,JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PAovTGVuZ3RoIDYgMCBSCi9GaWx0ZXIgL0ZsYXRlRGVjb2RlCj4+CnN0cmVhbQ=='
} else {
this.result = 'data:text/plain;base64,VGVzdCBmaWxlIGNvbnRlbnQ='
}
if (this.onload) this.onload({ target: this })
}, 0)
}
}
// Mock mammoth 全局对象
global.window = global.window || {}
global.window.mammoth = {
extractRawText: jest.fn().mockImplementation(async () => {
// 模拟DOCX文本提取
return {
value: 'Mock extracted text from DOCX file.\\n\\nThis is a sample document content for testing purposes.',
messages: []
}
})
}
// 增强 fetch Mock
const originalFetch = global.fetch
global.fetch = jest.fn().mockImplementation((url, options) => {
// 如果是外部API调用,返回mock响应
if (typeof url === 'string') {
if (url.includes('generativelanguage.googleapis.com')) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
candidates: [{
content: {
parts: [{
text: JSON.stringify({
title: 'Mock Presentation',
slides: [{ title: 'Mock Slide', bulletPoints: ['Point 1'], visualDescription: 'Mock description' }]
})
}]
}
}]
}),
body: {
getReader: () => ({
read: jest.fn()
.mockResolvedValueOnce({ done: false, value: new TextEncoder().encode('data: {"candidates":[{"content":{"parts":[{"text":"Mock"}]}}]}\\n\\n') })
.mockResolvedValueOnce({ done: true })
})
}
})
}
if (url.includes('api.openai.com')) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
choices: [{
message: {
content: 'Mock OpenAI response',
images: [{ image_url: { url: 'data:image/png;base64,mock-image' } }]
}
}]
}),
body: {
getReader: () => ({
read: jest.fn()
.mockResolvedValueOnce({ done: false, value: new TextEncoder().encode('data: {"choices":[{"delta":{"content":"Mock"}}]}\\n\\n') })
.mockResolvedValueOnce({ done: true })
})
}
})
}
}
// 对于内部API调用,使用原始fetch或MSW处理
return originalFetch ? originalFetch(url, options) : Promise.resolve({
ok: true,
json: () => Promise.resolve({ success: true })
})
})
// Mock ResizeObserver
global.ResizeObserver = jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
}))
// Mock IntersectionObserver
global.IntersectionObserver = jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
}))
// Mock URL.createObjectURL
global.URL.createObjectURL = jest.fn(() => 'mock-object-url')
global.URL.revokeObjectURL = jest.fn()
// Mock console methods to reduce noise in tests
const originalError = console.error
console.error = (...args) => {
if (
typeof args[0] === 'string' &&
(args[0].includes('Warning: ReactDOM.render is no longer supported') ||
args[0].includes('Warning: An invalid form control'))
) {
return
}
originalError.call(console, ...args)
}