{"id":17511,"library":"bedrock-test","title":"Bedrock Test Framework","description":"bedrock-test is a JavaScript testing utility for the Bedrock modular web application framework. It provides a structured approach for setting up and running tests, leveraging Mocha for backend unit tests and Karma (formerly Protractor, updated in search results to Karma) for frontend testing. The package, currently at version 6.1.0, is part of the Digital Bazaar Bedrock ecosystem, indicating its release cadence is likely tied to the development of the main Bedrock framework. Key differentiators include its ability to create self-contained test environments for individual modules, manage configuration overrides (e.g., `config.test.js` overriding `config.js`), and facilitate the inclusion of helper functions and mock data for comprehensive testing scenarios. It aims to simplify complex testing setups within the Bedrock architecture by defining how test files are loaded and executed, supporting a modular and independent testing approach for Bedrock-based projects.","status":"active","version":"6.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/digitalbazaar/bedrock-test","tags":["javascript","bedrock test"],"install":[{"cmd":"npm install bedrock-test","lang":"bash","label":"npm"},{"cmd":"yarn add bedrock-test","lang":"bash","label":"yarn"},{"cmd":"pnpm add bedrock-test","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for the core Bedrock framework, essential for its functionality and event system.","package":"bedrock","optional":false}],"imports":[{"note":"While the README examples primarily use CommonJS `require`, modern Bedrock applications increasingly utilize ES Modules. Import as a namespace for direct utility access. The package also often works by augmenting the global `bedrock` object on `require`.","wrong":"const bedrockTest = require('bedrock-test');","symbol":"bedrockTest","correct":"import * as bedrockTest from 'bedrock-test';"},{"note":"bedrock-test integrates deeply with the main `bedrock` framework's event system. Direct imports from `@bedrock/core` are common for core framework interactions. The `bedrock.test.configure` event is emitted by `bedrock-test`.","wrong":"const bedrock = require('bedrock');\nbedrock.events.on('bedrock.test.configure', configureTest);","symbol":"bedrock.events","correct":"import * as bedrock from '@bedrock/core';\nbedrock.events.on('bedrock.test.configure', configureTest);"},{"note":"Configuration for Mocha test files is often managed via `config.mocha.tests` within `test.config.js`. When using ESM, `__dirname` needs to be polyfilled. In older CJS setups, `__dirname` is globally available.","wrong":"config.mocha.tests.push(path.join(__dirname, 'mocha'));","symbol":"config.mocha.tests","correct":"// In test.config.js\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconfig.mocha.tests.push(path.join(__dirname, 'mocha'));"}],"quickstart":{"code":"import path from 'path';\nimport { fileURLToPath } from 'url';\nimport * as bedrock from '@bedrock/core';\nimport chai from 'chai';\nimport { describe, it, before, after } from 'mocha';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst expect = chai.expect;\n\n// Minimal Bedrock setup (typically done in a main test.js file)\nbedrock.events.on('bedrock.test.configure', configureTest);\nbedrock.events.on('bedrock.test.run', () => console.log('Tests starting...'));\nbedrock.start().catch(err => {\n  console.error('Bedrock failed to start:', err);\n  process.exit(1);\n});\n\nfunction configureTest(config) {\n  // Load module-specific test configuration\n  config.mocha = config.mocha || {};\n  config.mocha.tests = config.mocha.tests || [];\n  // Example: push a directory containing Mocha test files\n  config.mocha.tests.push(path.join(__dirname, 'mocha'));\n  // Example: configuration override (gotcha #1)\n  config.someFeature = { enabled: false };\n  config.test = { someFeature: { enabled: true } }; // This will override config.someFeature\n  console.log('Bedrock test configuration applied.');\n}\n\n// Example mock data (mock.data.js)\nconst mockData = {\n  user: { id: 'user123', name: 'Test User' },\n  product: { id: 'prod456', name: 'Test Product' }\n};\n\n// Example Mocha test file (e.g., test/mocha/00-user-api.js)\ndescribe('User API', () => {\n  let db = [];\n\n  before(async () => {\n    // Simulate loading mock data into a 'database'\n    db.push(mockData.user);\n    console.log('Setup: User added to mock DB.');\n  });\n\n  after(() => {\n    // Clean up between tests or after all tests\n    db = [];\n    console.log('Cleanup: Mock DB cleared.');\n  });\n\n  it('should retrieve the test user', () => {\n    const user = db.find(item => item.id === 'user123');\n    expect(user).to.exist;\n    expect(user.name).to.equal('Test User');\n    console.log('Test: User retrieved successfully.');\n  });\n\n  it('should not find a non-existent user', () => {\n    const user = db.find(item => item.id === 'nonexistent');\n    expect(user).to.not.exist;\n    console.log('Test: Non-existent user not found (as expected).');\n  });\n});","lang":"typescript","description":"This quickstart demonstrates how to set up a `bedrock-test` environment, configure it to load Mocha test files, handle mock data, and execute a basic Mocha test suite within the Bedrock framework. It also illustrates the configuration override pattern."},"warnings":[{"fix":"Upgrade Node.js to at least v10.12.0 or newer for `bedrock@3.x` and later. Ensure your `package.json` engines field reflects this.","message":"The Bedrock framework (and by extension `bedrock-test`) updated its Node.js requirement to v10.12.0 in `bedrock@3.0.0`, and later to `>=8` in `bedrock@1.18.0` due to async/await usage. Ensure your environment meets these minimums, as older Node.js versions will cause failures.","severity":"breaking","affected_versions":"<3.0.0"},{"fix":"Refactor `bedrock.start()` calls from `bedrock.start(callback)` to `await bedrock.start()` or `bedrock.start().then(...)`.","message":"As of `bedrock@3.0.0`, `bedrock.start()` now returns a Promise instead of using a callback. Code relying on the callback pattern for `bedrock.start()` must be updated to use `async/await` or `.then/.catch` for proper asynchronous handling.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Migrate all testing logic to use the `bedrock-test` module (version 4 and above) and its exposed APIs. Ensure `bedrock-test` is installed and configured correctly.","message":"The core `bedrock` framework removed its internal Mocha unit test framework in `bedrock@2.0.0`, relocating all testing functionality entirely to the `bedrock-test` module at version `bedrock-test@4`. Direct usage of internal `bedrock` testing utilities is no longer supported.","severity":"breaking","affected_versions":">=2.0.0 of bedrock"},{"fix":"Be explicit about configuration overrides in `config.test.js`. Review the Bedrock configuration loading order to understand which settings take precedence during test runs.","message":"When configuring tests, `config.test.js` files are loaded after `config.js` files. This means that any settings defined in `config.test.js` will override identical settings in `config.js`. This is by design for test environments but can lead to unexpected behavior if not understood.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For new projects, adopt ESM `import` statements and configure Node.js for ESM. For existing CJS projects, ensure consistency. If migrating, consider tools like `esm` or updating your build process.","message":"The `README` excerpts show `require()` syntax (CommonJS). While `bedrock-test` itself might still support CJS, modern Node.js and Bedrock applications increasingly use ES Modules (`import`/`export`). Mixing CJS `require` with ESM `import` can lead to module resolution issues or unexpected behavior without proper configuration (e.g., `\"type\": \"module\"` in `package.json` and correct file extensions).","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure `bedrock-test` is listed in your `package.json` and run `npm install` (or `yarn add bedrock-test`). Verify that the module resolution path is correct if using custom configurations.","cause":"The `bedrock-test` package or its dependencies were not properly installed or are not resolvable in the current environment.","error":"Error: Cannot find module 'bedrock-test'"},{"fix":"Ensure `require('@bedrock/core')` or `import '@bedrock/core';` is executed early in your test setup process, typically in the main `test.js` file, before `bedrock-test` is loaded. `bedrock.start()` should also be called.","cause":"The core `bedrock` framework has not been loaded or initialized before `bedrock-test` attempts to interact with it, specifically its event system or global configuration object.","error":"ReferenceError: bedrock is not defined"},{"fix":"Verify that `config.mocha.tests` correctly pushes the directories or specific file paths where your Mocha test files (`.js`) are located. Ensure the paths are absolute and correct, especially when using `path.join` and `__dirname`.","cause":"The `config.mocha.tests` array in `test.config.js` or equivalent configuration is incorrectly populated, or the specified test file paths are invalid.","error":"Mocha tests are not running or only a subset of tests are executing."},{"fix":"Ensure that `import * as bedrock from '@bedrock/core';` is at the top of your main test file and that any event subscriptions for `bedrock.events` occur after `bedrock` has been fully loaded. Consider `await bedrock.start()` to ensure the framework is ready.","cause":"The `bedrock` core module might not be fully initialized or `bedrock.events` is not available at the time of subscription. This often happens if the `bedrock` module is not correctly imported or if its initialization is deferred.","error":"TypeError: Cannot read properties of undefined (reading 'on') for bedrock.events"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}