0
# Test Configuration
1
2
Ice.js provides comprehensive testing integration with helpers for configuring Jest and Vitest with framework-specific optimizations, module resolution, and build pipeline integration.
3
4
## Capabilities
5
6
### Jest Configuration
7
8
Configure Jest with Ice.js framework defaults, module resolution, and optimizations.
9
10
```typescript { .api }
11
/**
12
* Define Jest configuration with Ice.js defaults and optimizations
13
* @param userConfig - Jest configuration object or async function returning config
14
* @returns Function that returns Promise resolving to complete Jest configuration
15
*/
16
function defineJestConfig(
17
userConfig: JestConfig | (() => Promise<JestConfig>)
18
): () => Promise<JestConfig>;
19
20
interface JestConfig {
21
/** Test environment */
22
testEnvironment?: 'node' | 'jsdom' | string;
23
/** Setup files to run before tests */
24
setupFilesAfterEnv?: string[];
25
/** Module name mapping for path aliases */
26
moduleNameMapper?: Record<string, string>;
27
/** File extensions to handle */
28
moduleFileExtensions?: string[];
29
/** Transform configuration */
30
transform?: Record<string, string | [string, any]>;
31
/** Files to collect coverage from */
32
collectCoverageFrom?: string[];
33
/** Coverage thresholds */
34
coverageThreshold?: {
35
global?: {
36
branches?: number;
37
functions?: number;
38
lines?: number;
39
statements?: number;
40
};
41
};
42
/** Test match patterns */
43
testMatch?: string[];
44
/** Files to ignore */
45
testPathIgnorePatterns?: string[];
46
/** Module paths to ignore */
47
modulePathIgnorePatterns?: string[];
48
[key: string]: any;
49
}
50
```
51
52
**Usage Examples:**
53
54
```typescript
55
// jest.config.js
56
import { defineJestConfig } from "@ice/app";
57
58
export default defineJestConfig({
59
testEnvironment: 'jsdom',
60
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
61
moduleNameMapper: {
62
'^@/(.*)$': '<rootDir>/src/$1',
63
'^@components/(.*)$': '<rootDir>/src/components/$1',
64
'\\.(css|less|scss|sass)$': 'identity-obj-proxy'
65
},
66
collectCoverageFrom: [
67
'src/**/*.{ts,tsx}',
68
'!src/**/*.d.ts',
69
'!src/**/*.stories.{ts,tsx}'
70
],
71
coverageThreshold: {
72
global: {
73
branches: 80,
74
functions: 80,
75
lines: 80,
76
statements: 80
77
}
78
}
79
});
80
81
// Dynamic configuration with async function
82
export default defineJestConfig(async () => {
83
const baseConfig = {
84
testEnvironment: 'jsdom',
85
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts']
86
};
87
88
// Load additional configuration based on environment
89
if (process.env.CI) {
90
return {
91
...baseConfig,
92
coverageReporters: ['text', 'lcov'],
93
reporters: ['default', 'jest-junit']
94
};
95
}
96
97
return {
98
...baseConfig,
99
coverageReporters: ['text', 'html']
100
};
101
});
102
```
103
104
### Vitest Configuration
105
106
Configure Vitest with Ice.js framework integration and optimizations.
107
108
```typescript { .api }
109
/**
110
* Define Vitest configuration with Ice.js defaults and optimizations
111
* @param userConfig - Vitest user configuration
112
* @returns Vitest configuration function
113
*/
114
function defineVitestConfig(userConfig: UserConfigExport): UserConfigFn;
115
116
type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFn;
117
type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
118
119
interface UserConfig {
120
/** Test configuration */
121
test?: VitestConfig;
122
/** Build configuration */
123
build?: BuildOptions;
124
/** Plugin configuration */
125
plugins?: Plugin[];
126
/** Alias configuration */
127
resolve?: {
128
alias?: Record<string, string>;
129
};
130
/** Define global constants */
131
define?: Record<string, any>;
132
[key: string]: any;
133
}
134
135
interface VitestConfig {
136
/** Test environment */
137
environment?: 'node' | 'jsdom' | 'happy-dom';
138
/** Globals configuration */
139
globals?: boolean;
140
/** Setup files */
141
setupFiles?: string[];
142
/** Include patterns */
143
include?: string[];
144
/** Exclude patterns */
145
exclude?: string[];
146
/** Coverage configuration */
147
coverage?: {
148
provider?: 'v8' | 'istanbul';
149
reporter?: string[];
150
exclude?: string[];
151
thresholds?: {
152
lines?: number;
153
functions?: number;
154
branches?: number;
155
statements?: number;
156
};
157
};
158
}
159
```
160
161
**Usage Examples:**
162
163
```typescript
164
// vitest.config.ts
165
import { defineVitestConfig } from "@ice/app";
166
167
export default defineVitestConfig({
168
test: {
169
environment: 'jsdom',
170
globals: true,
171
setupFiles: ['./src/setupTests.ts'],
172
include: ['src/**/*.{test,spec}.{ts,tsx}'],
173
exclude: ['node_modules', 'dist'],
174
coverage: {
175
provider: 'v8',
176
reporter: ['text', 'html', 'clover', 'json'],
177
exclude: [
178
'node_modules/',
179
'src/setupTests.ts',
180
'**/*.d.ts',
181
'**/*.stories.{ts,tsx}'
182
],
183
thresholds: {
184
lines: 80,
185
functions: 80,
186
branches: 80,
187
statements: 80
188
}
189
}
190
},
191
resolve: {
192
alias: {
193
'@': './src',
194
'@components': './src/components',
195
'@utils': './src/utils'
196
}
197
},
198
define: {
199
__TEST__: true
200
}
201
});
202
203
// Advanced configuration with plugins and custom settings
204
import { defineVitestConfig } from "@ice/app";
205
import react from '@vitejs/plugin-react';
206
207
export default defineVitestConfig({
208
plugins: [react()],
209
test: {
210
environment: 'jsdom',
211
globals: true,
212
setupFiles: ['./src/test/setup.ts'],
213
include: ['src/**/*.{test,spec}.{ts,tsx}'],
214
exclude: [
215
'node_modules',
216
'dist',
217
'build',
218
'**/*.e2e.{test,spec}.{ts,tsx}'
219
],
220
coverage: {
221
provider: 'v8',
222
reporter: ['text', 'json-summary', 'html'],
223
exclude: [
224
'node_modules/',
225
'src/test/',
226
'**/*.d.ts',
227
'**/*.config.{ts,js}',
228
'**/index.ts' // Barrel files
229
]
230
},
231
testTimeout: 10000,
232
hookTimeout: 10000
233
},
234
resolve: {
235
alias: {
236
'@': './src',
237
'@test': './src/test'
238
}
239
}
240
});
241
```
242
243
### Test Configuration Integration
244
245
Integrate test configurations with Ice.js build pipeline and development workflow.
246
247
```typescript { .api }
248
/**
249
* Test configuration utilities
250
*/
251
interface TestConfigurationUtils {
252
/** Get task configuration for test command */
253
getTaskConfig(): TaskConfig;
254
/** Merge test configuration with framework defaults */
255
mergeTestConfig(userConfig: any, defaults: any): any;
256
}
257
```
258
259
**Usage Examples:**
260
261
```typescript
262
// Custom test configuration setup
263
import { defineJestConfig, defineVitestConfig } from "@ice/app";
264
265
// Shared test utilities
266
const sharedTestConfig = {
267
moduleNameMapper: {
268
'^@/(.*)$': '<rootDir>/src/$1',
269
'^@components/(.*)$': '<rootDir>/src/components/$1',
270
'^@utils/(.*)$': '<rootDir>/src/utils/$1'
271
},
272
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
273
testPathIgnorePatterns: [
274
'/node_modules/',
275
'/dist/',
276
'/build/'
277
]
278
};
279
280
// Jest configuration for unit tests
281
export const jestConfig = defineJestConfig({
282
...sharedTestConfig,
283
testEnvironment: 'jsdom',
284
testMatch: [
285
'<rootDir>/src/**/__tests__/**/*.{ts,tsx}',
286
'<rootDir>/src/**/*.{test,spec}.{ts,tsx}'
287
],
288
collectCoverageFrom: [
289
'src/**/*.{ts,tsx}',
290
'!src/**/*.d.ts',
291
'!src/**/{stories,__tests__}/**',
292
'!src/test/**'
293
]
294
});
295
296
// Vitest configuration for integration tests
297
export const vitestConfig = defineVitestConfig({
298
test: {
299
environment: 'jsdom',
300
include: ['src/**/*.integration.{test,spec}.{ts,tsx}'],
301
testTimeout: 30000
302
},
303
resolve: {
304
alias: {
305
'@': './src',
306
'@components': './src/components'
307
}
308
}
309
});
310
```
311
312
### Framework-Specific Test Setup
313
314
Configure testing with Ice.js-specific setup and mocking.
315
316
```typescript { .api }
317
/**
318
* Ice.js-specific test setup utilities
319
*/
320
interface IceTestSetup {
321
/** Mock Ice.js runtime modules */
322
mockRuntimeModules(): void;
323
/** Setup test environment for Ice.js components */
324
setupTestEnvironment(): void;
325
/** Create test utilities for Ice.js features */
326
createTestUtils(): TestUtils;
327
}
328
329
interface TestUtils {
330
/** Render component with Ice.js providers */
331
renderWithProviders(component: React.ReactElement): RenderResult;
332
/** Mock router for testing */
333
mockRouter(routes: RouteConfig[]): void;
334
/** Setup mock server for API tests */
335
setupMockServer(): MockServer;
336
}
337
```
338
339
**Usage Examples:**
340
341
```typescript
342
// setupTests.ts - Test environment setup
343
import '@testing-library/jest-dom';
344
345
// Mock Ice.js runtime modules
346
jest.mock('@ice/runtime', () => ({
347
useAppData: jest.fn(),
348
usePageLifecycle: jest.fn(),
349
history: {
350
push: jest.fn(),
351
replace: jest.fn(),
352
go: jest.fn()
353
}
354
}));
355
356
// Mock Ice.js app configuration
357
jest.mock('./ice.config.ts', () => ({
358
default: {
359
router: {
360
type: 'browser'
361
},
362
server: {
363
format: 'esm'
364
}
365
}
366
}));
367
368
// Global test utilities
369
global.renderWithIceProviders = (component: React.ReactElement) => {
370
return render(component, {
371
wrapper: ({ children }) => (
372
<Router>
373
<AppProvider>
374
{children}
375
</AppProvider>
376
</Router>
377
)
378
});
379
};
380
381
// Test utilities file - testUtils.ts
382
import { render, RenderResult } from '@testing-library/react';
383
import { Router } from 'react-router-dom';
384
import { createMemoryHistory } from 'history';
385
386
export function renderWithRouter(
387
component: React.ReactElement,
388
{ initialEntries = ['/'], ...options } = {}
389
): RenderResult & { history: any } {
390
const history = createMemoryHistory({ initialEntries });
391
392
const Wrapper = ({ children }: { children: React.ReactNode }) => (
393
<Router location={history.location} navigator={history}>
394
{children}
395
</Router>
396
);
397
398
return {
399
...render(component, { wrapper: Wrapper, ...options }),
400
history
401
};
402
}
403
404
export function mockApiResponse(url: string, response: any) {
405
fetchMock.mockResponseOnce(JSON.stringify(response));
406
}
407
408
// Usage in tests
409
import { renderWithRouter, mockApiResponse } from '../testUtils';
410
import { MyComponent } from './MyComponent';
411
412
describe('MyComponent', () => {
413
test('renders with router integration', () => {
414
const { getByText, history } = renderWithRouter(<MyComponent />);
415
416
expect(getByText('Welcome')).toBeInTheDocument();
417
418
// Test navigation
419
fireEvent.click(getByText('Navigate'));
420
expect(history.location.pathname).toBe('/dashboard');
421
});
422
423
test('handles API calls', async () => {
424
mockApiResponse('/api/user', { name: 'John', id: 1 });
425
426
render(<MyComponent />);
427
428
await waitFor(() => {
429
expect(screen.getByText('John')).toBeInTheDocument();
430
});
431
});
432
});
433
```
434
435
### Testing Best Practices
436
437
Best practices for testing Ice.js applications with the provided configuration helpers.
438
439
```typescript { .api }
440
/**
441
* Testing best practices for Ice.js applications
442
*/
443
interface TestingBestPractices {
444
/** Component testing patterns */
445
componentTesting: {
446
unitTests: string[];
447
integrationTests: string[];
448
e2eTests: string[];
449
};
450
/** Mock strategies */
451
mockingStrategies: {
452
runtimeModules: string[];
453
apiCalls: string[];
454
routerMocks: string[];
455
};
456
/** Performance testing */
457
performanceTesting: {
458
bundleSize: boolean;
459
renderPerformance: boolean;
460
memoryLeaks: boolean;
461
};
462
}
463
```
464
465
**Usage Examples:**
466
467
```typescript
468
// Component testing example
469
import { defineJestConfig } from "@ice/app";
470
471
export default defineJestConfig({
472
testEnvironment: 'jsdom',
473
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
474
475
// Organize tests by type
476
projects: [
477
{
478
displayName: 'unit',
479
testMatch: ['<rootDir>/src/**/*.test.{ts,tsx}'],
480
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts']
481
},
482
{
483
displayName: 'integration',
484
testMatch: ['<rootDir>/src/**/*.integration.test.{ts,tsx}'],
485
setupFilesAfterEnv: [
486
'<rootDir>/src/setupTests.ts',
487
'<rootDir>/src/setupIntegrationTests.ts'
488
],
489
testTimeout: 30000
490
}
491
],
492
493
// Coverage configuration
494
collectCoverageFrom: [
495
'src/**/*.{ts,tsx}',
496
'!src/**/*.d.ts',
497
'!src/**/*.stories.{ts,tsx}',
498
'!src/test/**'
499
],
500
501
coverageThreshold: {
502
global: {
503
branches: 80,
504
functions: 85,
505
lines: 85,
506
statements: 85
507
},
508
// Specific thresholds for critical components
509
'./src/components/': {
510
branches: 90,
511
functions: 90,
512
lines: 90,
513
statements: 90
514
}
515
}
516
});
517
```
518
519
This testing configuration system provides comprehensive integration with Ice.js framework features while maintaining flexibility for custom test setups and advanced testing scenarios.