Mochapack: Webpack-integrated Mocha Test Runner

2.1.5 · active · verified Wed Apr 22

Mochapack is a command-line utility designed to seamlessly integrate Webpack's powerful asset compilation and module resolution directly into the Mocha test runner. Forked from the unmaintained `mocha-webpack`, it provides an optimized testing experience by precompiling test files with Webpack, automatically handling source maps, and avoiding temporary file writes to disk. A key differentiator is its 'watch' mode, which intelligently re-runs only the test files affected by a change, leveraging Webpack's dependency graph for efficient feedback during development. It aims to offer a CLI experience nearly identical to Mocha's, while enabling full Webpack benefits like custom path resolution within tests. The current stable version is 2.1.5, with releases typically occurring on a quarterly basis, focusing on dependency updates, Webpack/Mocha compatibility, and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up Mochapack with TypeScript, Webpack, and Mocha. It includes `package.json` scripts, a basic Webpack configuration for testing Node.js environments, and a sample TypeScript test file. The setup shows how to run tests using a glob pattern and register `ts-node` for TypeScript compilation on the fly.

// First, install dependencies:
// npm install --save-dev mocha webpack mochapack ts-node chai

// package.json (excerpt)
// {
//   "devDependencies": {
//     "mocha": "^9.0.0",
//     "webpack": "^5.0.0",
//     "mochapack": "^2.0.0",
//     "ts-node": "^10.0.0",
//     "chai": "^4.0.0"
//   },
//   "scripts": {
//     "test": "mochapack --require ts-node/register \"test/**/*.spec.ts\""
//   }
// }

// webpack.config.test.js (simplified example)
const nodeExternals = require('webpack-node-externals');

module.exports = {
  mode: 'development',
  target: 'node',
  externals: [nodeExternals()],
  devtool: 'inline-cheap-module-source-map',
  resolve: {
    extensions: ['.ts', '.js', '.json']
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: { transpileOnly: true }
      }
    ]
  }
};

// test/calculator.spec.ts
import { expect } from 'chai';
import { describe, it } from 'mocha';

class Calculator {
  add(a: number, b: number): number { return a + b; }
  subtract(a: number, b: number): number { return a - b; }
}

describe('Calculator', () => {
  const calculator = new Calculator();

  it('should correctly add two numbers', () => {
    expect(calculator.add(2, 3)).to.equal(5);
  });

  it('should correctly subtract two numbers', () => {
    expect(calculator.subtract(5, 2)).to.equal(3);
  });
});

// To run these tests: npm test

view raw JSON →