Testing JavaScript Module Pattern
Introduction
Testing JavaScript code that follows the Module Pattern requires verifying both private and public functionality. Since private methods and
variables are not directly accessible, testing focuses mainly on the public API of the module. Various testing frameworks like Jest, Mocha, and
Jasmine can be used to automate tests.
Example: Module to Test
Consider a simple Calculator Module implemented using the Module Pattern.
const Calculator = (function() {
let result = 0; // Private variable
function validateNumber(n) {
return typeof n === 'number' && !isNaN(n);
}
return {
add: function(n) {
if (validateNumber(n)) result += n;
return result;
},
subtract: function(n) {
if (validateNumber(n)) result -= n;
return result;
},
reset: function() {
result = 0;
return result;
},
getResult: function() {
return result;
}
};
})();
Unit Testing with Jest
Jest is a popular JavaScript testing framework. Install Jest using npm:
npm install --save-dev jest
Create a test file calculator.test.js:
const Calculator = require('./calculator'); // Import the module if using CommonJS
describe('Calculator Module', () => {
beforeEach(() => {
Calculator.reset(); // Reset state before each test
});
test('should add numbers correctly', () => {
expect(Calculator.add(5)).toBe(5);
expect(Calculator.add(10)).toBe(15);
});
test('should subtract numbers correctly', () => {
Calculator.add(10); // Set initial value
expect(Calculator.subtract(4)).toBe(6);
});
test('should return result', () => {
Calculator.add(20);
expect(Calculator.getResult()).toBe(20);
});
test('should reset correctly', () => {
Calculator.add(10);
Calculator.reset();
expect(Calculator.getResult()).toBe(0);
});
});
Run the tests with:
npx jest
Testing with Mocha & Chai
Mocha is another widely used testing framework, often paired with Chai for assertions.
Install Mocha and Chai:
npm install --save-dev mocha chai
Create a test file calculator.test.js:
const { expect } = require('chai');
const Calculator = require('./calculator');
describe('Calculator Module', function() {
beforeEach(function() {
Calculator.reset();
});
it('should add numbers correctly', function() {
expect(Calculator.add(5)).to.equal(5);
expect(Calculator.add(10)).to.equal(15);
});
it('should subtract numbers correctly', function() {
Calculator.add(10);
expect(Calculator.subtract(4)).to.equal(6);
});
it('should reset correctly', function() {
Calculator.add(10);
Calculator.reset();
expect(Calculator.getResult()).to.equal(0);
});
});
Run the tests with:
npx mocha
Conclusion
Testing JavaScript modules ensures code reliability and maintainability. By focusing on the public API, unit tests can verify expected behavior
while keeping private functions encapsulated. Using Jest or Mocha with Chai makes writing and running tests straightforward, improving code
quality over time.