Member-only story
The good old Table Testing approach
More often than not I find myself in the need to test a piece of code like the following
const formatHourFromAMPMto24 = (hour, period) => {
// ...
// Some addition and substraction logic that converts
// an AMPM formatted hour to 24 hour format and returns it
}
Simple enough to test right? Let’s write a couple of test cases that cover some inputs and output situations. Oh and let’s also make sure that we cover some edge cases, like 12PM and 12AM.
A couple minutes later you find yourself with something like this
it('returns 5 for 5AM', () => {
expect(formatHourFromAMPMto24(5, 'AM')).toEqual(5)
})
it('returns 17 for 5PM', () => {
expect(formatHourFromAMPMto24(5, 'PM')).toEqual(17)
})
it('returns 0 for 12AM', () => {
expect(formatHourFromAMPMto24(12, 'AM')).toEqual(0)
})
it('returns 12 for 12PM', () => {
expect(formatHourFromAMPMto24(12, 'PM')).toEqual(12)
})
// ...
Got that 🔔 ringing deep inside your coding brain? Everything looks pretty much the same, we are repeating the test code every time when just the inputs and outputs are different.
Good for us tests are also code! We should try to follow the DRY principle on tests just as we normally do.