Linting and Unit Tests

Linting and Unit Tests
Photo by Christopher Robin Ebbinghaus / Unsplash

Linting and Unit Tests Overview (JavaScript)

This is the long-awaited part 2 of the “how-to” article about the JavaScript Universe. If you haven’t checked it out or you are new to JavaScript I recommend reading through that article: How to make sense of the javascript universe

This is more geared to Managers, and those who are new to Linting and Testing. It is aimed to provide an overview and some tips to get you started quickly.

What is Linting?

In a nutshell, Linting is a process of checking the code to see if syntactically it is according to some standard. you can read more in-depth on Wikipedia. More specifically it is used in the interpreted languages or dynamically typed languages.

Assume you are coding in C#, when you define a string, it is not permissible to assign a decimal number:

string st = “test”;

st = 45.67;

This will result in a compilation error, and if such a thing happens at runtime, you will get an Exception. Most of these errors could be caught when compiling the application, But this is not the case for Dynamically Typed Languages like JavaScript, or PHP. That is completely legal to assign a string to a previously defined boolean.

To remedy this problem to a degree, Linting is used. Linting also is used to enforce a certain coding style. For example even single line ‘if’ statements should have a curly brace, or there should be or shouldn’t be a space between the if and parenthesis like “if (a<5)< strong>” or “if(a<5)< strong>“, these can be enforced by linting.

You can enforce linting in your transpilation pipeline so that if these rules are not obeyed, it can be considered an error and transpilation will stop. There are many packages for JavaScript, the famous one being ESLint, to check the code and make sure you are not missing a semicolon, if the function call was correct, if the correct spacing is used, for example, some developers prefer a space after their functions,

function a(){};

function a() {};

It is possible to enforce all kinds of rules to make sure everyone on the team is writing code in the same style. We can check linting as part of unit tests, and fail the build if there is any problem, this will make sure everyone follows the rules 🙂

If you are using Visual Studio Code, one of my favorite plugins is called Beautify, after you run your code, on each file, just press “F1” and then type Beautify, it will beautify your code! it is running js-beautify behind the scene, and in general, I find it a very handy tool.

It is also worth mentioning that there is another Library called Uglify :), It is used to minify (make it hard to read, and smaller download size) your JavaScript code when you want to publish your code to production. Also for TypeScript,a similar package exists, you guessed it, tslist.

Happy Coding!