I'm making an API using NestJS (NodeJS) and in order to run it in local enviromment without having all external APIs running, i want to mock the calls to external APIs while my API running.
In order to do this, I choose Json-server to do it, Here is the code:
mockserver.ts:
export async function bootstrap() {
const app = create();
app.use(
defaults({
logger: true,
static: 'static',
}),
router(dbJSON),
jsonServer.rewriter(routesJSON),
);
app.use('/api', router);
}
i tried also :
export async function bootstrap() {
const app = create();
app.use(
defaults({
logger: true,
static: 'static',
}),
router(db),
jsonServer.rewriter(routesJSON),
);
app.use('/api', router);
const port = process.env.mockPort ?? 8080;
app.listen(port);
main.ts :
async function bootstrap() {
const app = await NestFactory.create(AppModule)
const mocks = await import('../mocks/server');
app.use(await mocks.bootstrap(null));
await app.listen(DEFAULT_HTTP_PORT, DEFAULT_HOST);
}
However, instead of mocking the calls to external APIs using the db and the routes given to Json-server, my API itself was mocked.
Any ideas on how can I mock an API calls to external API while running? or how to make json-server mock call httpService calls only instead of the API itself
I haven't tried this before, but I think you either need to configure the existing HttpModule to sometimes forward calls or wrap HttpModule with a new module that decides whether or not to forward requests to the real server or mock server.
You can give HttpModule
a configuration via register. See the async configuration if you want to inject ConfigService
to configure it based off of an environment variable that determines if you're local or not. The config object is an Axios request config. However, I don't see a way to redirect requests via config.
HttpModule
uses axios
, so another option would be axios interceptors. In a request interceptor, you could have it only override config.url
when running locally. To set up interceptors at the beginning of the app, you could create a module MyHttpModule
that injects HttpService
, and in an onModuleInit
, get a reference to the axios instance and set the interceptors. Check out this example I found.