DEV Community

Cover image for How test script help you write a safety code?
Edwin Wong
Edwin Wong

Posted on • Edited on

How test script help you write a safety code?

Code without test script is like writing an essay without proofreading. End up, full of grammar mistake and typo and is kinda bad for reader. Same goes to code will become buggy and not reliable.

Write a test script may not completely away from bug but it also depends on how comprehensive test you write, the more comprehensive test the more code confident you have.

Let's look at this example...

function multiply(num1, num2) {
  return num1 * num2
}

multiply(1, 2) // 2
Enter fullscreen mode Exit fullscreen mode

It is a simple multiply function, now let's write test for this function.

test('with 1 * 2', () => {
  expect(multiply(1, 2)).toBe(2)
})

test('with times zero', () => {
  expect(multiply(1, 0)).toBe(0)
})
Enter fullscreen mode Exit fullscreen mode

Now, your code is tested but not completely. Let's see...

multiply(2) // NaN
multiply('o', 1) // NaN
multiply() // NaN
Enter fullscreen mode Exit fullscreen mode

See~ We often write the test script in our expected way. This will only ensure the result is expected provided with valid input. What about invalid input? To write a better test script you have to think in negative or unexpected way.

So, we need to improve our function handling.

function multiply(num1, num2) {
  if (!num1 || !num2) throw 'Invalid or missing params'
  return num1 * num2
}
Enter fullscreen mode Exit fullscreen mode

and update our test script also.

test('without input', () => {
  expect(multiply()).toBeThrow()
})

test('with invalid input', () => {
  expect(multiply(null, 2)).toBeThrow()
  expect(multiply(null, undefined)).toBeThrow()
})
Enter fullscreen mode Exit fullscreen mode

You think now is safe, but not yet! let's see this...

multiply('a', 'b') // NaN
Enter fullscreen mode Exit fullscreen mode

Gotcha! the way we check is only for parameter undefined or empty. By passing in 2 params with different type it still can pass our test. Let's improve again.

function multiply(num1, num2) {
  if (!num1 || !num2) throw 'Invalid or missing params'
  if (!/^[0-9]+/.test(num1) || !/^[0-9]+/.test(num2)) throw 'Invalid params'
  return num1 * num2
}

// test script
test('with invalid input', () => {
  expect(multiply(null, 2)).toBeThrow()
  expect(multiply(null, undefined)).toBeThrow()
  expect(multiply('a','b')).toBeThrow()
})

Enter fullscreen mode Exit fullscreen mode

Now, our test is comprehensive and bug free. During development, you may not cover all the use case to test and it is also impossible to know all the use case. That's fine, just fix it while you face it.

The more use case are cover the less bug that we can ensure.

Thank you for Reading!

feel free to comment is there a better way!

Top comments (0)