Skip to content
The Chat Archive
claude-opus-4-20250514· Anthropic LMArena Human Preference 140K

Give a detailed example of documenting a JSDoc class with unit tests written in JS and…

  1. User

    Give a detailed example of documenting a JSDoc class with unit tests written in JS and using the jest testing framework.

  2. Assistant

    Here's a comprehensive example of a JavaScript class with JSDoc documentation and Jest unit tests:

    The Class: Calculator.js

    /**
     * A simple calculator class that performs basic arithmetic operations.
     * @class Calculator
     * @example
     * const calc = new Calculator();
     * const sum = calc.add(5, 3); // returns 8
     */
    class Calculator {
      /**
       * Creates an instance of Calculator.
       * @constructor
       * @param {number} [precision=2] - The number of decimal places for results
       * @throws {Error} Throws an error if precision is negative
       */
      constructor(precision = 2) {
        if (precision < 0) {
          throw new Error('Precision must be non-negative');
        }
        this.precision = precision;
      }
    
      /**
       * Adds two numbers together.
       * @param {number} a - The first number
       * @param {number} b - The second number
       * @returns {number} The sum of a and b
       * @example
       * calculator.add(2, 3); // returns 5
       * calculator.add(0.1, 0.2); // returns 0.3 (with proper precision)
       */
      add(a, b) {
        return this._round(a + b);
      }
    
      /**
       * Subtracts the second number from the first.
       * @param {number} a - The number to subtract from
       * @param {number} b - The number to subtract
       * @returns {number} The difference of a and b
       */
      subtract(a, b) {
        return this._round(a - b);
      }
    
      /**
       * Multiplies two numbers.
       * @param {number} a - The first number
       * @param {number} b - The second number
       * @returns {number} The product of a and b
       */
      multiply(a, b) {
        return this._round(a * b);
      }
    
      /**
       * Divides the first number by the second.
       * @param {number} a - The dividend
       * @param {number} b - The divisor
       * @returns {number} The quotient of a and b
       * @throws {Error} Throws an error if attempting to divide by zero
       */
      divide(a, b) {
        if (b === 0) {
          throw new Error('Division by zero is not allowed');
        }
        return this._round(a / b);
      }
    
      /**
       * Calculates the power of a number.
       * @param {number} base - The base number
       * @param {number} exponent - The exponent
       * @returns {number} The result of base raised to the exponent
       */
      power(base, exponent) {
        return this._round(Math.pow(base, exponent));
      }
    
      /**
       * Calculates the square root of a number.
       * @param {number} n - The number to find the square root of
       * @returns {number} The square root of n
       * @throws {Error} Throws an error if n is negative
       */
      sqrt(n) {
        if (n < 0) {
          throw new Error('Cannot calculate square root of negative number');
        }
        return this._round(Math.sqrt(n));
      }
    
      /**
       * Private method to round numbers to the specified precision.
       * @private
       * @param {number} num - The number to round
       * @returns {number} The rounded number
       */
      _round(num) {
        return Math.round(num * Math.pow(10, this.precision)) / Math.pow(10, this.precision);
      }
    
      /**
       * Gets the current precision setting.
       * @returns {number} The current precision value
       */
      getPrecision() {
        return this.precision;
      }
    
      /**
       * Sets a new precision value.
       * @param {number} newPrecision - The new precision value
       * @throws {Error} Throws an error if precision is negative
       */
      setPrecision(newPrecision) {
        if (newPrecision < 0) {
          throw new Error('Precision must be non-negative');
        }
        this.precision = newPrecision;
      }
    }
    
    module.exports = Calculator;
    

    The Test File: Calculator.test.js

    const Calculator = require('./Calculator');
    
    /**
     * Test suite for the Calculator class
     */
    describe('Calculator', () => {
      let calculator;
    
      // Setup before each test
      beforeEach(() => {
        calculator = new Calculator();
      });
    
      describe('Constructor', () => {
        test('should create calculator with default precision of 2', () => {
          expect(calculator.getPrecision()).toBe(2);
        });
    
        test('should create calculator with custom precision', () => {
          const customCalc = new Calculator(4);
          expect(customCalc.getPrecision()).toBe(4);
        });
    
        test('should throw error for negative precision', () => {
          expect(() => new Calculator(-1)).toThrow('Precision must be non-negative');
        });
      });
    
      describe('Addition', () => {
        test('should add two positive numbers', () => {
          expect(calculator.add(2, 3)).toBe(5);
        });
    
        test('should add negative numbers', () => {
          expect(calculator.add(-5, -3)).toBe(-8);
        });
    
        test('should add decimal numbers with precision', () => {
          expect(calculator.add(0.1, 0.2)).toBe(0.3);
        });
    
        test('should handle zero', () => {
          expect(calculator.add(5, 0)).toBe(5);
          expect(calculator.add(0, 0)).toBe(0);
        });
      });
    
      describe('Subtraction', () => {
        test('should subtract two numbers', () => {
          expect(calculator.subtract(10, 3)).toBe(7);
        });
    
        test('should handle negative results', () => {
          expect(calculator.subtract(3, 10)).toBe(-7);
        });
    
        test('should subtract decimal numbers', () => {
          expect(calculator.subtract(5.5, 2.3)).toBe(3.2);
        });
      });
    
      describe('Multiplication', () => {
        test('should multiply two positive numbers', () => {
          expect(calculator.multiply(4, 5)).toBe(20);
        });
    
        test('should multiply with negative numbers', () => {
          expect(calculator.multiply(-4, 5)).toBe(-20);
          expect(calculator.multiply(-4, -5)).toBe(20);
        });
    
        test('should multiply by zero', () => {
          expect(calculator.multiply(100, 0)).toBe(0);
        });
    
        test('should multiply decimal numbers', () => {
          expect(calculator.multiply(2.5, 4)).toBe(10);
        });
      });
    
      describe('Division', () => {
        test('should divide two numbers', () => {
          expect(calculator.divide(10, 2)).toBe(5);
        });
    
        test('should handle decimal division', () => {
          expect(calculator.divide(10, 3)).toBe(3.33);
        });
    
        test('should throw error for division by zero', () => {
          expect(() => calculator.divide(10, 0)).toThrow('Division by zero is not allowed');
        });
    
        test('should divide negative numbers', () => {
          expect(calculator.divide(-10, 2)).toBe(-5);
          expect(calculator.divide(-10, -2)).toBe(5);
        });
      });
    
      describe('Power', () => {
        test('should calculate power of positive numbers', () => {
          expect(calculator.power(2, 3)).toBe(8);
        });
    
        test('should handle power of zero', () => {
          expect(calculator.power(5, 0)).toBe(1);
        });
    
        test('should handle negative exponents', () => {
          expect(calculator.power(2, -2)).toBe(0.25);
        });
    
        test('should handle fractional exponents', () => {
          expect(calculator.power(4, 0.5)).toBe(2);
        });
      });
    
      describe('Square Root', () => {
        test('should calculate square root of positive numbers', () => {
          expect(calculator.sqrt(9)).toBe(3);
          expect(calculator.sqrt(16)).toBe(4);
        });
    
        test('should calculate square root of decimal', () => {
          expect(calculator.sqrt(2)).toBe(1.41);
        });
    
        test('should throw error for negative numbers', () => {
          expect(() => calculator.sqrt(-4)).toThrow('Cannot calculate square root of negative number');
        });
    
        test('should handle zero', () => {
          expect(calculator.sqrt(0)).toBe(0);
        });
      });
    
      describe('Precision', () => {
        test('should round results according to precision', () => {
          calculator.setPrecision(1);
          expect(calculator.add(1.14, 1.15)).toBe(2.3);
          
          calculator.setPrecision(3);
          expect(calculator.add(1.1234, 1.1234)).toBe(2.247);
        });
    
        test('should update precision', () => {
          calculator.setPrecision(5);
          expect(calculator.getPrecision()).toBe(5);
        });
    
        test('should throw error for negative precision in setter', () => {
          expect(() => calculator.setPrecision(-1)).toThrow('Precision must be non-negative');
        });
    
        test('should handle zero precision', () => {
          calculator.setPrecision(0);
          expect(calculator.add(1.7, 1.7)).toBe(3);
        });
      });
    
      describe('Edge Cases', () => {
        test('should handle very large numbers', () => {
          expect(calculator.add(1e10, 1e10)).toBe(2e10);
        });
    
        test('should handle very small numbers', () => {
          calculator.setPrecision(10);
          expect(calculator.add(1e-10, 1e-10)).toBe(2e-10);
        });
    
        test('should handle Infinity', () => {
          expect(calculator.add(Infinity, 1)).toBe(Infinity);
          expect(calculator.multiply(Infinity, 0)).toBe(NaN);
        });
      });
    });
    

    Package.json Configuration

    {
      "name": "calculator-example",
      "version": "1.0.0",
      "description": "Example of JSDoc documentation with Jest tests",
      "main": "Calculator.js",
      "scripts": {
        "test": "jest",
        "test:watch": "jest --watch",
        "test:coverage": "jest --coverage",
        "docs": "jsdoc Calculator.js -d docs"
      },
      "devDependencies": {
        "jest": "^29.0.0",
        "jsdoc": "^4.0.0"
      },
      "jest": {
        "testEnvironment": "node",
        "coverageDirectory": "coverage",
        "collectCoverageFrom": [
          "**/*.js",
          "!**/*.test.js",
          "!**/node_modules/**"
        ]
      }
    }
    

    Running the Tests

    To run these tests, you would use the following commands:

    # Run all tests
    npm test
    
    # Run tests in watch mode
    npm run test:watch
    
    # Run tests with coverage report
    npm run test:coverage
    
    # Generate JSDoc documentation
    npm run docs
    

    This example demonstrates several important concepts:

    1. JSDoc annotations include @class, @constructor, @param, @returns, @throws, @example, and @private tags
    2. Test organization using describe blocks to group related tests
    3. Setup and teardown with beforeEach to create fresh instances
    4. Testing various scenarios including normal cases, edge cases, and error conditions
    5. Assertion methods using Jest's expect() with various matchers
    6. Error testing using expect().toThrow()
    7. Coverage considerations by testing different code paths and edge cases

    The tests cover constructor validation, all public methods, error handling, precision settings, and edge cases like division by zero or negative square roots. This provides a solid foundation for maintaining code quality and catching regressions.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.