{"id":13602195,"url":"https://github.com/microcks/microcks-testcontainers-node","last_synced_at":"2026-01-29T19:22:08.817Z","repository":{"id":191167901,"uuid":"683075936","full_name":"microcks/microcks-testcontainers-node","owner":"microcks","description":"Node/TypeScript lib for Testcontainers that enables embedding Microcks into your unit tests with lightweight, throwaway instance thanks to containers.","archived":false,"fork":false,"pushed_at":"2024-10-21T15:38:17.000Z","size":401,"stargazers_count":9,"open_issues_count":3,"forks_count":2,"subscribers_count":4,"default_branch":"main","last_synced_at":"2024-10-30T05:42:58.537Z","etag":null,"topics":["api","graphql","grpc","mocking","nodejs","rest","testcontainers","testing","typescript"],"latest_commit_sha":null,"homepage":"https://microcks.io","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microcks.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":"SECURITY-INSIGHTS.yml","support":null,"governance":"GOVERNANCE.md","roadmap":"ROADMAP.md","authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"microcks","patreon":null,"open_collective":"microcks","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2023-08-25T14:38:23.000Z","updated_at":"2024-10-21T15:38:13.000Z","dependencies_parsed_at":"2024-11-07T05:33:15.550Z","dependency_job_id":"6dac858f-56be-4e6b-8ce9-5f86e85f1e19","html_url":"https://github.com/microcks/microcks-testcontainers-node","commit_stats":{"total_commits":80,"total_committers":5,"mean_commits":16.0,"dds":0.275,"last_synced_commit":"ea2df0e4d5f6629eb4b69fb2f80b93499b3f53ad"},"previous_names":["microcks/microcks-testcontainers-node"],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microcks%2Fmicrocks-testcontainers-node","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microcks%2Fmicrocks-testcontainers-node/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microcks%2Fmicrocks-testcontainers-node/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microcks%2Fmicrocks-testcontainers-node/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microcks","download_url":"https://codeload.github.com/microcks/microcks-testcontainers-node/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224869081,"owners_count":17383311,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","graphql","grpc","mocking","nodejs","rest","testcontainers","testing","typescript"],"created_at":"2024-08-01T18:01:16.124Z","updated_at":"2026-01-29T19:22:08.812Z","avatar_url":"https://github.com/microcks.png","language":"TypeScript","funding_links":["https://github.com/sponsors/microcks","https://opencollective.com/microcks"],"categories":["api"],"sub_categories":[],"readme":"# Microcks Testcontainers Node\n\nNode/TypeScript library for Testcontainers that enables embedding Microcks into your unit tests with lightweight, throwaway instance thanks to containers\n\nWant to see this extension in action? Check out our [sample application](https://github.com/microcks/microcks-testcontainers-node-nest-demo). 🚀\n\n[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/microcks/microcks-testcontainers-node/build-verify.yml?logo=github\u0026style=for-the-badge)](https://github.com/microcks/microcks-testcontainers-node/actions)\n[![Version](https://img.shields.io/npm/v/@microcks/microcks-testcontainers?color=blue\u0026style=for-the-badge)](https://www.npmjs.com/package/@microcks/microcks-testcontainers)\n[![License](https://img.shields.io/github/license/microcks/microcks-testcontainers-java?style=for-the-badge\u0026logo=apache)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Project Chat](https://img.shields.io/badge/discord-microcks-pink.svg?color=7289da\u0026style=for-the-badge\u0026logo=discord)](https://microcks.io/discord-invite/)\n[![Artifact HUB](https://img.shields.io/endpoint?url=https://artifacthub.io/badge/repository/microcks-uber-image\u0026style=for-the-badge)](https://artifacthub.io/packages/search?repo=microcks-uber-image)\n[![CNCF Landscape](https://img.shields.io/badge/CNCF%20Landscape-5699C6?style=for-the-badge\u0026logo=cncf)](https://landscape.cncf.io/?item=app-definition-and-development--application-definition-image-build--microcks)\n\n### Table of Contents\n\n[Build Status](#build-status)  \n[Community](#community)  \n[How to use it?](#how-to-use-it)  \n- [Include it into your project dependencies](#include-it-into-your-project-dependencies)\n- [Startup the container](#startup-the-container)\n- [Import content in Microcks](#import-content-in-microcks)\n- [Using mock endpoints for your dependencies](#using-mock-endpoints-for-your-dependencies)\n- [Verifying mock endpoint has been invoked](#verifying-mock-endpoint-has-been-invoked)\n- [Launching new contract-tests](#launching-new-contract-tests)\n- [Using authentication Secrets](#using-authentication-secrets)\n- [Advanced features with MicrocksContainersEnsemble](#advanced-features-with-microckscontainersensemble)\n  - [Postman contract-testing](#postman-contract-testing)\n  - [Asynchronous API support](#asynchronous-api-support)\n    - [Using mock endpoints for your dependencies](#using-mock-endpoints-for-your-dependencies-1)\n    - [Launching new contract-tests](#launching-new-contract-tests-1)\n- [Troubleshooting](#troubleshooting)\n\n## Build Status\n\nLatest released version is `0.3.4`.\n\nCurrent development version is `0.3.5-SNAPSHOT`.\n\n#### Fossa license and security scans\n\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fmicrocks%2Fmicrocks-testcontainers-node.svg?type=shield\u0026issueType=license)](https://app.fossa.com/projects/git%2Bgithub.com%2Fmicrocks%2Fmicrocks-testcontainers-node?ref=badge_shield\u0026issueType=license)\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fmicrocks%2Fmicrocks-testcontainers-node.svg?type=shield\u0026issueType=security)](https://app.fossa.com/projects/git%2Bgithub.com%2Fmicrocks%2Fmicrocks-testcontainers-node?ref=badge_shield\u0026issueType=security)\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fmicrocks%2Fmicrocks-testcontainers-node.svg?type=small)](https://app.fossa.com/projects/git%2Bgithub.com%2Fmicrocks%2Fmicrocks-testcontainers-node?ref=badge_small)\n\n#### OpenSSF best practices on Microcks core\n\n[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/7513/badge)](https://bestpractices.coreinfrastructure.org/projects/7513)\n[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/microcks/microcks/badge)](https://securityscorecards.dev/viewer/?uri=github.com/microcks/microcks)\n\n## Community\n\n* [Documentation](https://microcks.io/documentation/tutorials/getting-started/)\n* [Microcks Community](https://github.com/microcks/community) and community meeting\n* Join us on [Discord](https://microcks.io/discord-invite/), on [GitHub Discussions](https://github.com/orgs/microcks/discussions) or [CNCF Slack #microcks channel](https://cloud-native.slack.com/archives/C05BYHW1TNJ)\n\nTo get involved with our community, please make sure you are familiar with the project's [Code of Conduct](./CODE_OF_CONDUCT.md).\n\n## How to use it?\n\n### Include it into your project dependencies\n\n```sh\nnpm install @microcks/microcks-testcontainers\n```\n\n### Startup the container\n\nYou just have to specify the container image you'd like to use. This library requires a Microcks `uber` distribution (with no MongoDB dependency).\n\n```ts\nimport { MicrocksContainer } from \"@microcks/microcks-testcontainers\";\n\nconst container = await new MicrocksContainer().start();\n```\n\n### Import content in Microcks\n\nTo use Microcks mocks or contract-testing features, you first need to import OpenAPI, Postman Collection, GraphQL or gRPC artifacts. \nArtifacts can be imported as main/Primary ones or as secondary ones. See [Multi-artifacts support](https://microcks.io/documentation/explanations/multi-artifacts/) for details.\n\nYou can do it before starting the container using arrays of paths:\n\n```ts\nimport * as path from \"path\";\n\nconst resourcesDir = path.resolve(__dirname, \"..\", \"test-resources\");\n\nconst container = await new MicrocksContainer()\n    .withMainArtifacts([path.resolve(resourcesDir, \"apipastries-openapi.yaml\")])\n    .withSecondaryArtifacts([path.resolve(resourcesDir, \"apipastries-postman-collection.json\")])\n    .start();\n\n```\n\nor once the container is started :\n\n```ts\nimport * as path from \"path\";\n\nconst resourcesDir = path.resolve(__dirname, \"..\", \"test-resources\");\n\nawait container.importAsMainArtifact(path.resolve(resourcesDir, \"apipastries-openapi.yaml\"));\nawait container.importAsSecondaryArtifact(path.resolve(resourcesDir, \"apipastries-postman-collection.json\"));\n```\n\nPlease refer to our [MicrocksContainerTest](https://github.com/microcks/microcks-testcontainers-node/blob/main/src/microcks-container.test.ts) for comprehensive example on how to use it.\n\nStarting with version `0.2.4` you can also import full \n[repository snapshots](https://microcks.io/documentation/guides/administration/snapshots/) at once:\n\n```ts\nimport * as path from \"path\";\n\nconst resourcesDir = path.resolve(__dirname, \"..\", \"test-resources\");\n\nconst container = await new MicrocksContainer()\n    .withSnapshots([path.resolve(resourcesDir, \"microcks-repository.json\")])\n    .start();\n```\n\n### Using mock endpoints for your dependencies\n\nDuring your test setup, you'd probably need to retrieve mock endpoints provided by Microcks containers to \nsetup your base API url calls. You can do it like this:\n\n```ts\n// Get base Url for API Pastries / 0.0.1\nvar pastriesUrl = container.getRestMockEndpoint(\"API Pastries\", \"0.0.1\");\n```\n\nThe container provides methods for different supported API styles/protocols (Soap, GraphQL, gRPC,...).\n\nThe container also provides `getHttpEndpoint()` for raw access to those API endpoints.\n\n### Verifying mock endpoint has been invoked\n\nOnce the mock endpoint has been invoked, you'd probably need to ensure that the mock have been really invoked.\n\nYou can do it like this :\n\n```ts\nexpect(await container.verify(\"API Pastries\", \"0.0.1\")).toBe(true);\n```\n\nOr like this :\n\n```ts\nconst serviceInvocationsCount: number = await container.getServiceInvocationsCount(\"API Pastries\", \"0.0.1\");\n```\n\n### Launching new contract-tests\n\nIf you want to ensure that your application under test is conformant to an OpenAPI contract (or many contracts),\nyou can launch a Microcks contract/conformance test using the local server port you're actually running:\n\n```ts\nimport { MicrocksContainer, TestRequest, TestRunnerType } from \"@microcks/microcks-testcontainers\";\n\nvar testRequest: TestRequest = {\n    serviceId: \"API Pastries:0.0.1\",\n    runnerType: TestRunnerType.OPEN_API_SCHEMA,\n    testEndpoint: \"http://bad-impl:3001\",\n    timeout: 2000\n}\n\nvar testResult = await container.testEndpoint(testRequest);\n\nexpect(testResult.success).toBe(false);\nexpect(testResult.testedEndpoint).toBe(\"http://bad-impl:3001\");\nexpect(testResult.testCaseResults.length).toBe(3);\nexpect(testResult.testCaseResults[0].testStepResults[0].message).toContain(\"object has missing required properties\");\n```\n\nThe `TestResult` gives you access to all details regarding success of failure on different test cases.\n\nIn addition, you can use the `getMessagesForTestCase()` method to retrieve the messages exchanged during the test.\n\nA comprehensive NestJS demo application illustrating both usages is available here: [nest-order-service](https://github.com/microcks/api-lifecycle/tree/master/shift-left-demo/nest-order-service).\n\n### Using authentication Secrets\n\nIt's a common need to authenticate to external systems like Http/Git repositories or external brokers. For that, the `MicrocksContainer` provides the `withSecret()` method to register authentication secrets at startup:\n\n```ts\nmicrocks.withSecret({\n        name: 'localstack secret',\n        username: 'test',\n        password: 'test'\n    })\n    .start();\n```\n\nYou may reuse this secret using its name later on during a test like this:\n\n```ts\nconst testRequest: TestRequest = {\n    serviceId: \"Pastry orders API:0.1.0\",\n    runnerType: TestRunnerType.ASYNC_API_SCHEMA,\n    testEndpoint: \"sqs://us-east-1/pastry-orders?overrideUrl=http://localstack:4566\",\n    secretName: \"localstack secret\",\n    timeout: 5000\n}\n```\n\nYou may also reference secrets when downloading remote artifacts:\n\n```ts\nmicrocksContainer\n  .withMainRemoteArtifacts([\n    { url: \"https://gitlab.com/user/private_repo/artifact1.yaml\", secretName: \"gl-secret\" },\n    \"https://github.com/user/public_repo/artifact2.yaml\"\n  ])\n  .withSecondaryRemoteArtifacts([\n    { url: \"https://gitlab.com/user/private_repo/examples1.yaml\", secretName: \"gl-secret\" },\n    \"https://github.com/user/public_repo/examples2.yaml\"\n  ]);\n```\n\n\n### Advanced features with MicrocksContainersEnsemble\n\nThe `MicrocksContainer` referenced above supports essential features of Microcks provided by the main Microcks container. The list of supported features is the following:\n\n* Mocking of REST APIs using different kinds of artifacts,\n* Contract-testing of REST APIs using `OPEN_API_SCHEMA` runner/strategy,\n* Mocking and contract-testing of SOAP WebServices,\n* Mocking and contract-testing of GraphQL APIs,\n* Mocking and contract-testing of gRPC APIs.\n\nTo support features like Asynchronous API and `POSTMAN` contract-testing, we introduced `MicrocksContainersEnsemble` that allows managing additional Microcks services. MicrocksContainersEnsemble allow you to implement [Different levels of API contract testing](https://medium.com/@lbroudoux/different-levels-of-api-contract-testing-with-microcks-ccc0847f8c97) in the Inner Loop with Testcontainers!\n\nA `MicrocksContainersEnsemble` conforms to Testcontainers lifecycle methods and presents roughly the same interface as a `MicrocksContainer`. You can create and build an ensemble that way after having initialized a `Network`:\n\n```ts\nimport { Network } from \"testcontainers\";\nimport { MicrocksContainer } from \"@microcks/microcks-testcontainers\";\n\nconst network = await new Network().start();\n\nconst ensemble = await new MicrocksContainersEnsemble(network)\n    .withMainArtifacts([path.resolve(resourcesDir, \"apipastries-openapi.yaml\")])\n    .withSecondaryArtifacts([path.resolve(resourcesDir, \"apipastries-postman-collection.json\")])\n    .start();\n```\n\nA `MicrocksContainer` is wrapped by an ensemble and is still available to import artifacts and execute test methods. You have to access it using:\n\n```ts\nconst microcks = ensemble.getMicrocksContainer();\nawait microcks.importAsMainArtifact(...);\n(await microcks.logs())\n  .on(\"data\", line =\u003e console.log(line))\n  .on(\"err\", line =\u003e console.error(line))\n  .on(\"end\", () =\u003e console.log(\"Stream closed\"));\n```\n\nPlease refer to our [MicrocksContainersEnsembleTest](https://github.com/microcks/microcks-testcontainers-node/blob/main/src/microcks-containers-ensemble.test.ts) for comprehensive example on how to use it.\n\n#### Postman contract-testing\n\nOn this `ensemble` you may want to enable additional features such as Postman contract-testing:\n\n```ts\nensemble.withPostman();\nensemble.start();\n```\n\nYou can execute a `POSTMAN`` test using an ensemble that way:\n\n```ts\nvar testRequest = {\n    serviceId: \"API Pastries:0.0.1\",\n    runnerType: TestRunnerType.POSTMAN,\n    testEndpoint: \"http://good-impl:3003\",\n    timeout: 3000\n}\n\nvar testResult = await ensemble.getMicrocksContainer().testEndpoint(testRequest);\n\nexpect(testResult.success).toBe(true);\nexpect(testResult.testedEndpoint).toBe(\"http://good-impl:3003\");\nexpect(testResult.testCaseResults.length).toBe(3);\nexpect(testResult.testCaseResults[0].testStepResults[0].message).toBeUndefined();\n```\n\n#### Asynchronous API support\n\nAsynchronous API feature need to be explicitly enabled as well. In the case you want to use it for mocking purposes,\nyou'll have to specify additional connection details to the broker of your choice. See an example below with connection\nto a Kafka broker:\n\n```ts\nensemble.withAsyncFeature()\n    .withKafkaConnection({\n        bootstrapServers: \"kafka:9092\"\n    });\nensemble.start();\n```\n\n##### Using mock endpoints for your dependencies\n\nOnce started, the `ensemble.getAsyncMinionContainer()` provides methods for retrieving mock endpoint names for the different\nsupported protocols (WebSocket, Kafka, SQS and SNS).\n\n```ts\nconst kafkaTopic = ensemble.getAsyncMinionContainer()\n    .getKafkaMockTopic(\"Pastry orders API\", \"0.1.0\", \"SUBSCRIBE pastry/orders\");\n```\n\n##### Launching new contract-tests\n\nUsing contract-testing techniques on Asynchronous endpoints may require a different style of interacting with the Microcks\ncontainer. For example, you may need to:\n1. Start the test making Microcks listen to the target async endpoint,\n2. Activate your System Under Tests so that it produces an event,\n3. Finalize the Microcks tests and actually ensure you received one or many well-formed events.\n\nAs the `MicrocksContainer` provides the `testEndpoint(request: TestRequest): Promise\u003cTestResult\u003e` method, this is actually easy like:\n\n```ts\n// Start the test, making Microcks listen the endpoint provided in testRequest\nlet testResultPromise: Promise\u003cTestResult\u003e = ensemble.getMicrocksContainer().testEndpoint(testRequest);\n\n// Here below: activate your app to make it produce events on this endpoint.\n// myapp.invokeBusinessMethodThatTriggerEvents();\n\n// Now retrieve the final test result and assert.\nlet testResult = await testResultPromise;\nexpect(testResult.success).toBe(true);\n```\n\nIn addition, you can use the `getEventMessagesForTestCase()` method to retrieve the events received during the test.\n\n### Troubleshooting\n\nYou can enable debug logs on the Microcks container by setting the debug log level and then retrieving the logs:\n\n```ts\nconst container = await new MicrocksContainer()\n    .withDebugLogLevel()\n    .withLogConsumer(stream =\u003e {\n        stream.on(\"data\", line =\u003e console.log(line));\n        stream.on(\"end\", () =\u003e console.log(\"Stream closed\"));\n    })\n    .start();\n```\n\nThe same `.withDebugLogLevel()` method is available on also `MicrocksContainersEnsemble` for enabling debug logs \non all contained Microcks containers.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrocks%2Fmicrocks-testcontainers-node","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmicrocks%2Fmicrocks-testcontainers-node","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrocks%2Fmicrocks-testcontainers-node/lists"}