Testing utility functions
Let's test our code now! Let's start with utils. Create a file called utils.spec.js
and import the leftPad
function:
import { leftPad } from '~/utils/utils'
Have a look at this function again:
// utils/utils.js export const leftPad = value => { if (('' + value).length > 1) { return value } return '0' + value }
This function should return the input string if this string's length is greater than 1
. If the string's length is 1
, it should return the string with a preceding 0
.
Seems quite easy to test it, right? We would write two test cases:
// test/utils.spec.js describe('utils', () => { describe('leftPad', () => { it('should return the string itself if its length is more than 1', () => { expect(leftPad('01')).toEqual('01') }) it('should add a 0 from the left if the entry string is of the length of 1', () => { expect(leftPad('0')).toEqual('00') }) }) })
Argh...if you run this test, you will get an error:
Of course...