testdouble.js (AKA td.js) is an opinionated, minimalist test double library for JavaScript and TypeScript, designed to facilitate test-driven development (TDD). It provides robust mechanisms for creating mocks, stubs, and spies to replace real dependencies within tests, promoting terse, clear, and easy-to-understand test suites. As of version 3.20.2, the library is actively maintained by Test Double, a software agency. It maintains a steady release cadence for bug fixes and minor features within its major versions. The library is framework-agnostic, compatible with popular test runners like Jest, Mocha, and Jasmine, and functions reliably in both Node.js and browser environments. Its primary differentiator is its strong opinions on TDD practices, aiming to guide developers toward healthier mocking patterns rather than simply offering a comprehensive feature set without guidance.
npm install testdoubleVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to create a test double for a class dependency using `td.object`, stub its methods with `td.when().thenReturn()`, and verify interactions with `td.verify()` within a `mocha`-like test structure. It also shows `td.reset()` for cleanup and basic argument matching.
Review the official documentation for `td.replace()` and `td.replaceEsm()`. Ensure `td.replaceEsm()` is used for ES Modules, requiring specific build tool configurations (e.g., Vite, Webpack, Node's `--loader`) to work correctly.
Configure your linter (e.g., ESLint, StandardJS) to acknowledge `td` as a global variable. Refer to your linter's documentation for adding global exclusions.
Always use `td.replaceEsm()` when mocking ES Modules. Be aware that `td.replaceEsm()` might require specific test environment setups (e.g., Node.js with `--loader` flags or bundler configurations like Vite/Webpack) to intercept module imports effectively. Consult the `testdouble.js` documentation for detailed guidance on your module system.
Focus on testing behavior rather than implementation details. Use test doubles only for external dependencies that cannot be controlled in a test. Avoid mocking value objects or closely coupled internal components. Refer to the 'xUnit Test Patterns' book and `testdouble.js`'s extensive documentation on healthy TDD practices.
Ensure `import * as td from 'testdouble'` (ESM) or `globalThis.td = require('testdouble')` (CommonJS) is executed before any `td` calls in your test files or setup scripts.Add `td` to your linter's global configuration. For ESLint, you might add `'td': true` under the `globals` section in your `.eslintrc` file.
When replacing the default export of an ESM, you typically provide the module path and then the *keyword* 'default' as the second argument, e.g., `td.replaceEsm('./my-module', 'default', () => ({...}))`. If targeting a named export, provide its specific name.No dependency data recorded yet.