Using NodeJs Unit Testing(Jest)

  • Why Unit Testing
    • project starts simple, but grows more and more complex
    • horrifying functions start a simple way
    • You must think longer than your nose goes(Swedish sayings proverb)
  • add shipping
    • if the total amount is greater than 1000, then it’s free
    • instead of thinking lots of cases at the same time, we break it down by several isolated steps
  • add taxes
  • Happy Test
    • the main function the most time program spend

TDD 3 ways

- obvious implementation
- fake it until you make it
- triangalation
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
function orderFilterTotal(order) {
// 直接返回結果不需要再用一個變數來接
// 三元表達式(item.quantity ? item.quantity : 1)
return order.items
.reduce((total, item) => {return (item.price * (item.quantity || 1) + total) }, 0);
}


if(orderFilterTotal({
items: [
{name:'cat food', price: 8, quantity: 2},
{name:'cat cage', price: 800, quantity: 3}
]
}) != 2416) {
throw new Error("Check Fail: Quantity Error)")
}

if(orderFilterTotal({
items: [
{name:'cat food', price: 3}
]
}) != 3) {
throw new Error("Check Fail: No Quantity")
}



if(orderFilterTotal({
items: [
{name:'cat food', price: 8},
{name:'cat cage', price: 800}
]
}) != 808) {
throw new Error("Check Fail: Happy Test(Example 1)")
}

if(orderFilterTotal({
items: [
{name:'cat toy', price: 30},
{name:'cat towel', price: 40}
]
}) != 70) {
throw new Error("Check Fail: Happy Test(Example 2)")
}

Jest Auto Test

  • You need to notice your test file name to be xxxx.test.js format
    • it doesn’t matter the test file goes, but the file name matter
1
2
3
4
5
// Happy Path
it('works', () => {
expect(1).toBe(1);
})