Module 72 : Linting, Formatting, and Testing in JavaScript
1. Introduction
JavaScript projects quickly grow in size and complexity. Without proper linting, formatting, and testing, developers face:
Inconsistent coding styles.
Hard-to-code.
Hidden bugs that are discovered late.
ESLint (for linting), Prettier (for formatting), and Testing frameworks (like Jest and Mocha). Together, they form the backbone of professional-grade JavaScript development.
2. Linting with ESLint
🔹 What is Linting?
Linting is the process of analyzing code for errors, bad practices, and style violations.
Helps catch bugs early.
Enforces coding standards.
Improves collaboration in teams.
🔹 Installing ESLint
npm init -y npm install eslint --save-dev
Initialize ESLint:
npx eslint --init
Choose:
Framework: "None" (if plain JS).
Style guide: "Airbnb" / "Standard" / "Google".
Format: JSON/YAML/JS for config.
This creates an .eslintrc.json file. Example:
{ "env": { "browser": true, "es2021": true }, "extends": ["eslint:recommended"], "rules": { "no-console": "warn", "semi": ["error", "always"] } }
🔹 Example
Code before ESLint:
function add(a, b) { return a + b } console.log(add(2,3))
ESLint Output:
Warn: Missing semicolon.
Warn: Unexpected console statement.
Corrected Code (after ESLint):
function add(a, b) { return a + b; } console.log(add(2, 3));
3. Formatting with Prettier
🔹 What is Prettier?
Opinionated code formatter.
Makes code style consistent across a project.
Works with ESLint (they complement each other).
🔹 Installing Prettier
npm install prettier --save-dev
Create a .prettierrc file:
{ "semi": true, "singleQuote": true, "trailingComma": "es5" }
🔹 Example
Messy Code:
function greet(name){console.log("Hello, "+name)} greet("Rehana")
After Prettier:
function greet(name) { console.log('Hello, ' + name); } greet('Rehana');
4. Combining ESLint and Prettier
ESLint = Catches errors + enforces rules.
Prettier = Handles code style/formatting.
To integrate:
npm install eslint-config-prettier eslint-plugin-prettier --save-dev
Update .eslintrc.json:
{ "extends": ["eslint:recommended", "plugin:prettier/recommended"] }
✅ Now, ESLint and Prettier work together — no conflicts.
5. Testing in JavaScript
🔹 Why Testing?
Testing ensures your code works as expected. Types:
Unit Tests: Test small functions (most common).
Integration Tests: Test multiple modules together.
End-to-End (E2E): Test entire workflows.
🔹 Using Jest (Popular Choice)
Install Jest:
npm install --save-dev jest
Update package.json:
"scripts": { "test": "jest" }
🔹 Example Test
math.js
function add(a, b) { return a + b; } module.exports = add;
math.test.js
const add = require('./math'); test('adds 2 + 3 to equal 5', () => { expect(add(2, 3)).toBe(5); });
Run tests:
npm test
✅ Output: PASS (if correct).
6. 1: ESLint + Prettier Setup
Create a new Node.js project.
Install ESLint and Prettier.
Configure ESLint (.eslintrc.json) to disallow console.log.
Write messy code with console.log.
Run ESLint and Prettier.
Observe auto-fix results.
Goal: Learn how tools enforce consistency.
2: Writing Tests
Create a function multiply(a, b) in math.js.
Write a Jest test math.test.js to check:
multiply(2, 3) → 6
multiply(5, 0) → 0
multiply(-2, 4) → -8
Run tests.
Goal: Understand how unit tests verify correctness.
3: Integrating Everything
Create a function divide(a, b) in math.js.
Add ESLint rules (no-undef, semi: always).
Use Prettier for consistent formatting.
Write Jest tests to handle edge cases:
Division by zero (should throw error).
Normal division.
Goal: Experience full pipeline: Lint → Format → Test.
7. Research Insights
Airbnb Style Guide + ESLint: Widely used in industry for consistent JavaScript coding standards.
Prettier: Saves time in code reviews by removing debates over formatting.
Jest: Dominant testing framework (used by Meta, React community).
Expert Advice:
“Automated linting and formatting reduce cognitive load and improve focus on logic instead of style.”
“Testing should be part of development, not an afterthought. Aim for at least 70–80% unit test coverage.”
8. Exercises
Configure ESLint to enforce camelCase variable names. Write code with snake_case and fix it.
Format a large messy file with Prettier and compare before/after.
unit tests for a function that finds the largest number in an array.
Create a mini-project: Calculator with add, subtract, multiply, divide, fully linted, formatted, and tested.
Understand how ESLint and Prettier enforce coding quality.
Know how to configure and use linting + formatting tools.
Be able to write and run unit tests in JavaScript.
that simulate workflows.
No comments:
Post a Comment