Blog>
Snippets

Simplifying Unit Testing Standalone Components

Demonstrate the advantages of testing standalone components which do not require the context of an entire module, making unit tests simpler and faster to run.
// A simple calculator component for demonstration
function Calculator() {
    // Method to add two numbers
    this.add = function (a, b) {
        return a + b;
    };
    // Method to subtract two numbers
    this.subtract = function (a, b) {
        return a - b;
    };
}
This is the standalone Calculator component with add and subtract methods, which can be easily unit tested without any external dependencies.
// Unit tests for the Calculator component using a basic testing framework (e.g., Jest)
describe('Calculator', () => {
    let calculator;
    // Setup the Calculator object before each test
    beforeEach(() => {
        calculator = new Calculator();
    });
    // Test the 'add' method
    test('adds 1 + 2 to equal 3', () => {
        expect(calculator.add(1, 2)).toBe(3);
    });
    // Test the 'subtract' method
    test('subtracts 2 - 1 to equal 1', () => {
        expect(calculator.subtract(2, 1)).toBe(1);
    });
});
The unit tests for the Calculator component, testing both the add and subtract methods in isolation. Using Jest test framework syntax for demonstration.