経験は何よりも饒舌

10年後に真価を発揮するかもしれないブログ 

Understanding the difference of Unit Test and Integration Test

Understanding the difference of Unit Test and Integration Test by testing add function and total function in App.js, using Jest and I quote Unit Test vs Integration Test: What's the Difference?.

export const add = (x, y) => x + y

export const total = (shipping, subtotal) => {
    return '$' + add(shipping, subtotal)
}

Unit Test

Test code and result is below.

import { add } from './App'

test('add', () => {
    expect(add(1, 2)).toBe(3)
    expect(add(3, 6)).toBe(9)
    expect(add(3, 6)).toBe(10)
})


The idea behind Unit Testing is to test each part of the program and show that the individual parts are correct.

It means this test show that add function is correct.

It is kind of White Box Testing

It means this Unit Test show that why test is not correct (3 plus 6 is not 9 but 10).

Integration Test

combine modules in the application and test as a group to see that they are working fine

It means this test show that total function that add function is combined with is correct.

The test written below passes.

import { total } from './App'

test('total', () => {
    expect(total(5, 20)).toBe('$25')
})

But if the add function behaves unintentionally like below, this test is not pass.

export const add = (x, y) => x - y  // oops!!

export const total = (shipping, subtotal) => {
    return '$' + add(shipping, subtotal)
}

Also if the total function behaves unintentionally like below, this test is not pass.

export const add = (x, y) => x + y

export const total = (shipping, subtotal) => {
    return '#' + add(shipping, subtotal) // oops!!
}


It is kind of Black Box Testing

It means you can't know which function is responsible for not passing the test(which function has bugs).
In this case, two functions is easy so it is easy to know it, but the bigger the code, the harder.


In this case, if change App.js like below, you just have to do Unit Test.

export const add = (x, y) => x + y
export const doller = () => '$'

export const total = (shipping, subtotal) => {
    return doller() + add(shipping, subtotal)
}
import { add, doller, total } from './App'

test('add', () => {
    expect(add(1, 2)).toBe(3)
})

test('doller', () => {
    expect(doller()).toBe('$')
})

// If add and doller pass, it will definitely pass
test('total', () => {
    expect(total(5, 20)).toBe('$25')
})