-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathmockHelpers.ts
More file actions
59 lines (55 loc) · 1.33 KB
/
mockHelpers.ts
File metadata and controls
59 lines (55 loc) · 1.33 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
import {jest} from '@jest/globals';
type SpyInstance = ReturnType<typeof jest.spyOn>;
/**
* Mocks Date constructor to return a specific timestamp
*
* @param timestamp - The timestamp value to return from new Date().getTime()
* @returns Jest spy object for the mocked Date constructor
*
* @example
* ```ts
* const spy = mockDateNow(1234567890);
* expect(new Date().getTime()).toBe(1234567890);
* spy.mockRestore();
* ```
*/
export const mockDateNow = (timestamp: number): SpyInstance => {
const spy = jest.spyOn(global, 'Date').mockImplementation(
() =>
({
getTime: () => timestamp,
} as any),
);
return spy;
};
/**
* Mocks Math.random() to return a specific value
*
* @param value - The value to return from Math.random() (should be between 0 and 1)
* @returns Jest spy object for the mocked Math.random()
*
* @example
* ```ts
* const spy = mockMathRandom(0.5);
* expect(Math.random()).toBe(0.5);
* spy.mockRestore();
* ```
*/
export const mockMathRandom = (value: number): SpyInstance => {
const spy = jest.spyOn(Math, 'random');
spy.mockReturnValue(value);
return spy;
};
/**
* Restores all mocks to their original implementations
*
* @example
* ```ts
* afterEach(() => {
* restoreAllMocks();
* });
* ```
*/
export const restoreAllMocks = (): void => {
jest.restoreAllMocks();
};