Why should I unit test my code?

Whether or not to write unit test cases for code

Image source: oseconsulting
Image source: guru99

As quoted by one of the articles here, unit tests are so important that they should be a first class language construct.

Me: Yes please.. it’s about time now!!

What is unit testing?

Example 1:

function addNumbers(num1, num2) {
return num1 + num2;
}
expect(addNumbers(5, 6)).toBe(11);
expect(addNumbers(-1, 9)).toBe(8);
// fails as with current implementation, result will be NaN
expect(addNumbers()).toBe(0);
// fails as with current implementation, result will be 'abcxyz' expect(addNumbers('abc', 'xyz')).toBe(0);
function addNumbers(num1, num2) {
return parseFloat(num1 + num2) || 0;
}

Example 2:

function getUserDetailsToDisplay(userDetails) {
return {
name: getFullName(userDetails.firstName, userDetails.lastName),
dateOfBirth: userDetails.dob || '-'
};
}
function getFullName(firstName = '', lastName = '') {
return (firstName + ' ' + lastName).trim() || '-';
}
const resultWithValidDetails = getUserDetailsToDisplay({
firstName: 'testFirstName',
lastName: 'testLastName',
dob: 'test date'
});
expect(resultWithValidDetails.name).toBe('testFirstName testLastName');
expect(resultWithValidDetails.dateOfBirth).toBe('test date');
const resultWithNoDetails = getUserDetailsToDisplay({});
expect(resultWithNoDetails.name).toBe('-');
expect(resultWithNoDetails.dateOfBirth).toBe('-');
function getUserDetailsToDisplay(userDetails) {
return {
name: getFullName(userDetails.firstName,
userDetails.middleName, userDetails.lastName),
dateOfBirth: userDetails.dob || '-'
};
}
Snapshot taken while preparing the example for this article
const resultWithValidDetails = getUserDetailsToDisplay({
firstName: 'testFirstName',
middleName: 'testMiddleName'
lastName: 'testLastName',
dob: 'test date'
});
expect(resultWithValidDetails.name).toBe('testFirstName testMiddleName testLastName');
expect(resultWithValidDetails.dateOfBirth).toBe('test date');
Snapshot taken while preparing the example for this article
function getFullName(firstName = '', middleName = '', lastName = '') {
return (firstName + ' ' + middleName + ' ' + lastName).trim() ||
'-';
}

Conclusion

Any code that is not unit tested is legacy code.

Image source: typemock

Tech enthusiast, Development Specialist @teammediaocean. Creator of https://explore-a11y.netlify.app/ My motto — ‘Choose RIGHT over easy, always!’

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store