Typically, when it comes to setting up integration tests and working with external dependencies, an approach is used where components are simulated through mocks. This means that database responses or requests via axios
are artificially replaced with pre-defined results directly in the code. Below you can see one of the example using such technique.
import axios from 'axios';
// Set up an interceptor to mock requests
axios.interceptors.request.use((config) => {
if (config.url === 'https://api.example.com') {
return Promise.resolve({
data: { result: 'mocked success' }
});
}
return config;
});
axios.get('https://api.example.com')
.then(response => console.log(response.data)) // Logs 'mocked success'
.catch(error => console.error(error));
If you want to test how your app interacts with external client or provider APIs without mocking tools like axios, consider the following solution called mockserver. This approach allows you to define expected request-response schemas, ensuring that your app reacts correctly to all possible scenarios from the provider API. For example, you can specify:
{
"httpRequest": {
"method": "GET",
"path": "/view/cart"
},
"httpResponse": {
"body": "some_response_body"
}
}
The schema can be more detailed based on your needs. Mocking the database or handling events in message brokers is simpler and typically hassle-free. The core Node.js code remains unchanged (apart from adjusting environment variables for API calls). Now your scenarios are thoroughly tested, giving you confidence that the behavior will be consistent in production.
- No Code Mocking: Focuses on testing real integrations, without relying on mocks or stubs in node.js.
- Production-like Testing: Verifies how the app interacts with external services in a more realistic, production-like environment.
- Supports External APIs: Tests real API interactions with services like databases or third-party providers using MockServer to define request-response pairs without hardcoding behavior.
- Node.js (v14.x or higher)
- docker-compose
-
Clone the repository:
git clone https://github.com/KHYehor/integration-tests.git cd integration-tests
-
Install dependencies:
npm install
-
Create a
.env
file to configure environment variables:cp .env.tests .env
-
Start up docker-compose daemon (depends on the operation system);
-
Now easily run tests with
npm run test:integration
or
npm run test:integration:testcontainers
.
.
├── src/
│ ├── ... # Example buisnes logic
├── tests # Integration tests with native docker-compose
├── tests-testcontainers # Integration tests using testcontainers library
└── README.md # Project documentation
- Node.js: Backend JavaScript runtime.
- Nest.js: Web framework for building the API.
- Docker-compose: PostgreSQL client for Node.js.
- jest: Testing framework for running the integration tests.
This project is licensed under the MIT License. See the LICENSE file for details.