How to test microservice with mocks from NestJS 2022
What are disadvantages of using microservices?
With the microservice approach, there is increased complexity in the support, especially with the strategies for testing. As with every part of the software, we can cover them with the unit tests, but due to the distributed nature of microservices, you can occur in the situation that there is a necessity to mock a lot of API calls, so the contract between microservices can be broken. To be able to correctly
Extract the OpenAPI schema from the NestJS application
In order to retrieve the schema from the NestJS application, you can create a script, which imports application module in the script and writes to the filesystem.
import { NestFactory } from "@nestjs/core";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { AppModule } from "../app.module";
import * as fs from 'fs';
const options = new DocumentBuilder()
.setTitle("Title")
.setDescription("description")
.setVersion("1.0")
.build();
NestFactory.create(AppModule).then((app) => {
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
fs.writeFileSync("./swagger-spec.json", JSON.stringify(document)); // write down the OpenAPI document
app.close(); // Exit the application without listening
});
Run the mock server from OpenAPI definition
After extracting the schema, you can utilize prism to start the mock server.
prism mock ./swagger-spec.json -p 3000 -h 0.0.0.0
After it, you should be able to see output, stating that mock server should be up and running
This setup allows you to provide necessary minimum mock server, which should be able to meet the requirements of your contract tests. You can put obtained OpenAPI JSON file and execute command above in your CI/CD setup.
Photo by Hal Gatewood on Unsplash