-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
61 lines (54 loc) · 1.66 KB
/
index.js
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
// Warning in case the passed value is not a decimal
// eslint-disable-next-line no-console
const showWarning = () => console.warn('WARNING: The value that you are using to mock random is not a decimal and it is breaking the real contract');
const isDecimal = number => number === 0 || (!Number.isNaN(number) && number % 1 !== 0);
const warnBrokenContract = (values) => {
if (!values.map(parseFloat).every(isDecimal)) {
showWarning();
}
};
// Copy the global Math object in order to reset it
const mathCopy = Object.create(global.Math);
const resetMockRandom = () => {
global.Math = mathCopy;
};
// randomMock implementation
const randomMock = (returnValues) => {
let arrayOfValues = returnValues;
if (!Array.isArray(returnValues)) {
arrayOfValues = [returnValues];
}
let index = 0;
return () => {
if (arrayOfValues.length === 0) {
throw new TypeError('The value list must contain some value');
}
warnBrokenContract(arrayOfValues);
if (index >= arrayOfValues.length) {
index = 0;
}
return arrayOfValues[index++];
};
};
// Through a copy of the global Math object we mock the random method
const mockRandom = (values) => {
const mockMath = Object.create(global.Math);
mockMath.random = randomMock(values);
global.Math = mockMath;
};
// When mockRandomWith is called it create the mock beforeEach and reset it after
const mockRandomForEach = (valuesArray) => {
// eslint-disable-next-line no-undef
beforeEach(() => {
mockRandom(valuesArray);
});
// eslint-disable-next-line no-undef
afterEach(() => {
resetMockRandom();
});
};
module.exports = {
mockRandomForEach,
mockRandom,
resetMockRandom,
};