Thursday, October 2, 2025

Javascript Module 73

  Module 73 : JavaScript Testing & Code Optimization (Jest & Mocha)

1.  Introduction: Why Testing & Optimization?

Testing ensures correctness, stability, and reliability of applications.








Optimization ensures better performance, readability, and maintainability.

Jest and Mocha are two widely used frameworks:

Jest (by Facebook): Easy setup, built-in mocks, great for React apps.

Mocha: Flexible, minimal, works with assertion libraries like Chai.

example: Imagine you have an e-commerce app. A broken calculateTotal(cart) function could cause serious revenue loss. Automated tests + optimization detect errors early and improve performance.


2.  Setup & Environment

Jest Installation

npm install --save-dev jest

Add script in package.json:

"scripts": { "test": "jest" }

Mocha Installation

npm install --save-dev mocha chai

Add script in package.json:

"scripts": { "test": "mocha" }


3. ✨ Writing Tests in Jest & Mocha


Example: Function to Test

// math.js function add(a, b) { return a + b; } function factorial(n) { if (n === 0) return 1; return n * factorial(n - 1); } module.exports = { add, factorial };


Jest Example

// math.test.js const { add, factorial } = require('./math'); test('adds two numbers correctly', () => { expect(add(2, 3)).toBe(5); }); test('calculates factorial correctly', () => { expect(factorial(5)).toBe(120); });

Run:

npm test


Mocha + Chai Example

// test/math.test.js const { expect } = require('chai'); const { add, factorial } = require('../math'); describe('Math Functions', () => { it('should add numbers correctly', () => { expect(add(2, 3)).to.equal(5); }); it('should calculate factorial correctly', () => { expect(factorial(5)).to.equal(120); }); });

Run:

npm test


4.  Code Optimization Through Testing

Before Optimization

function slowFactorial(n) { let result = 1; for (let i = 1; i <= n; i++) { result *= i; } return result; }

After Optimization (Memoization)

const memo = {}; function optimizedFactorial(n) { if (n in memo) return memo[n]; if (n === 0) return 1; return (memo[n] = n * optimizedFactorial(n - 1)); }

✅ Why better?

Saves repeated computations.

Faster for larger inputs.


5. Performance Testing Example










Using Jest with Benchmarking:

test('optimized factorial is faster', () => { const start = performance.now(); optimizedFactorial(1000); const optimizedTime = performance.now() - start; const slowStart = performance.now(); slowFactorial(1000); const slowTime = performance.now() - slowStart; expect(optimizedTime).toBeLessThan(slowTime); });


6. Exercises

Exercise 1: Optimize Array Search

Write a function to find duplicates in an array.

Test with Jest/Mocha.

Optimize using Set instead of nested loops.

Exercise 2: Refactor Sorting

Implement bubble sort.

Test correctness with Jest.

Optimize using JavaScript’s built-in sort().

Exercise 3: Mocking API Calls

Create a fake API function (fetch user data).

Use Jest’s mock functions to simulate responses.

// mock example jest.mock('./api', () => ({ fetchUser: jest.fn(() => Promise.resolve({ name: 'Alice' })) }));


7. Research 

Research Insight: Studies show that test-driven development (TDD) reduces bug density by 40–80% (Microsoft Research).


Keep tests small and focused.

Use coverage tools (jest --coverage).

Optimize code after tests pass.

Use mocks and spies for external dependencies.

Run tests in CI/CD pipelines (GitHub Actions, Jenkins).


8. Tips

Start with a story: "Imagine your online payment system crashes because of a missing test…"











 Demo: Write a function, add tests, then optimize it.

Encourage Debugging: Let students run failing tests and fix errors.

Assign exercises must improve performance.

Assessment: submit both tests + optimized code.


No comments:

Post a Comment

Javascript Module 78

  Javascript   Module 78 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test...