Writing unit-testable JavaScript code

Why Unit testing?

What is unit testing?

Benefits of unit testing

What makes your code testable?

// hard to test
$('#cta').on('click', () => {
$.get('/path/to/data').then(data => {
$('#target').html('items: ' + data.join(', '));
});
});
// Testable code
function fetchData(onSuccess) {
$.get('/path/to/data').then(onSuccess);
}
function renderData(data) {
$('#target').html('items: ' + data.join(', '));
}
$('#cta').on('click', () => fetchData(renderData);
// Hard to test
function handleLogin(name, pass) {
window.auth.login(name, pass);
}
// Testable
function handleLogin(name, pass, authHandler) {
authHandler.login(name, pass);
}
// Not unit testable
// Here its intended function is to add number but it does other thing also.
function add(a, b) {
let isString = (c)=> typeof c == 'string';
a = isString(a)? a.length : a;
b = isString(b)? b.length : b;
return a + b;
}
add(ipt1, ipt2);// Below is unit testable
function add(a, b) {
return a + b;
}
function isString(c) {
return typeof c == 'string';
}
function myLogic(a) {
reutn isString(a)? a.length : a;
}
add( myLogic(ipt1), myLogic(ipt2) );
// wrong
function addModified(userObj) {
userObj.modified = new Date();
return userObj;
}
// correct
function addModified(userObj) {
return {
...userObj,
modified: new Date()
};
}

My opinion.

--

--

--

Front-end developer | JS/React/Vue

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

FCF — Full Stack JavaScript Framework now supports macOS operating system.

5 Handlebars Helpers BigCommerce Developers Should Know

Line Chart D3.js &Angular

Start making a website with MERN stack?

MERN stack (MognoDB, React, Express and Node.js)

Configuring Swagger 2 with Spring Boot for RESTful API Documentation

Middleware in Next.js 12: What Are They and How to Get Started with Them?

The magic in Kotlin: Delegates

ExpressVPN review: A fine VPN service, but is it worth the price?

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
kamesh sethupathi

kamesh sethupathi

Front-end developer | JS/React/Vue

More from Medium

getting started with the JavaScript array sort() method

javascript use strict

Medium — Difference between find() and filter() in Javascript

Top 10 Must Know JavaScript Functions