Test Runner
Thenode:test module facilitates the creation of JavaScript tests. To access it:
node: scheme.
Basic Test Structure
Tests created via thetest module consist of a single function that is processed in one of three ways:
- Synchronous function - Considered failing if it throws an exception, passing otherwise
- Promise-returning function - Considered failing if the Promise rejects, passing if it fulfills
- Callback function - Receives a callback; failing if callback receives a truthy first argument, passing if it receives a falsy value
Writing Tests
Basic Examples
Subtests
The test context’stest() method allows subtests to be created, enabling hierarchical test structure:
await to ensure subtests complete before the parent test finishes. Any outstanding subtests when the parent finishes are cancelled and treated as failures.
describe() and it() Aliases
Tests can also be written usingdescribe() and it() functions:
Skipping Tests
Individual tests can be skipped:TODO Tests
Tests can be marked as TODO (pending implementation):Only Tests
When Node.js is started with the--test-only flag, only tests with the only option will run:
Filtering Tests by Name
Tests can be filtered using command-line options:Watch Mode
The test runner supports watch mode:Running Tests from Command Line
Invoke the test runner from the command line:**/*.test.{cjs,mjs,js}**/*-test.{cjs,mjs,js}**/*_test.{cjs,mjs,js}**/test-*.{cjs,mjs,js}**/test.{cjs,mjs,js}**/test/**/*.{cjs,mjs,js}
Test Hooks
Tests support setup and teardown hooks:Test Reporters
The test runner supports multiple reporters:Collecting Code Coverage
Collect code coverage with the--experimental-test-coverage flag:
Mocking
Function Mocking
Method Mocking
Timer Mocking
Date Mocking
Snapshot Testing
Snapshot tests allow values to be serialized and compared against known good values:Best Practices
- Use descriptive test names - Make it clear what each test is checking
- Keep tests focused - Each test should verify one specific behavior
- Use subtests for organization - Group related tests together
- Clean up after tests - Use
afterandafterEachhooks - Mock external dependencies - Keep tests isolated and fast
- Use watch mode during development - Get instant feedback on changes
- Check code coverage - Ensure your tests cover important code paths
- Use meaningful assertions - Make test failures easy to understand