-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnitTestsChallenge.js
More file actions
99 lines (81 loc) · 2.41 KB
/
UnitTestsChallenge.js
File metadata and controls
99 lines (81 loc) · 2.41 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
// not clean
// function addProduct(name, price) {
// if (!name || name.trim() === '' || !price || price < 0) {
// console.log('Invalid input - product was not created.');
// return;
// }
// const product = {
// id: name + '_' + Math.random().toString(),
// name: name,
// price: price,
// };
// database.insert('products', product);
// return product;
// }
//
// describe(function () {
// it('should create a product for valid names and prices', function () {
// const createdProduct = addProduct('Carpet', 19);
// expect(createdProduct).not.toBeUndefined();
// });
//
// it('should generate a product id that contains the product name', function () {
// const createdProduct = addProduct('Book', 19);
// expect(createdProduct.id).stringContaining('Book');
// });
// });
// clean
function addProduct(name, price) {
validateProductData(name, price);
const savedProduct = saveProduct(name, price);
return savedProduct;
}
function validateProductData(name, price) {
if (!inputIsValid(name, price)) {
throw new Error('Invalid input - product was not created.');
}
}
function inputIsValid(name, price) {
return !isEmpty(name) && hasMinValue(price, 0);
}
function isEmpty(value) {
return !value || value.trim() === '';
}
describe(function () {
it('return true if an empty name is passed as a value', function () {
const validationResult = isEmpty('');
expect(validationResult).toEqual(true);
});
it('return false if a non-empty name is passed as a value', function () {
const validationResult = isEmpty('Test');
expect(validationResult).toEqual(false);
});
});
function hasMinValue(value, minValue) {
return value > minValue;
}
describe(function () {
it('return true if a value above the minValue is provided', function () {
const validationResult = hasMinValue(10, 8);
expect(validationResult).toEqual(true);
});
it('return false if a value below the minValue is provided', function () {
const validationResult = hasMinValue(5, 8);
expect(validationResult).toEqual(false);
});
});
function showErrorMessage(message) {
console.log(message);
}
function saveProduct(name, price) {
const product = {
id: generateRandomId(name),
name: name,
price: price,
};
database.insert('products', product);
return product;
}
function generateRandomId(baseValue) {
return baseValue + '_' + Math.random().toString();
}