SkillByAIइंटरैक्टिव संस्करण खोलें →

पाठ 20 / 32

Routes को Test करना

fastify.inject और Node के built-in test runner से बिना असली server के Fastify routes तेज़ी से test करें।

In-process testing

Fastify directly requests inject कर सकता है बिना real server शुरू किए—unit और integration tests के लिए आदर्श।

Inject के साथ testing

Requests भेजने और responses को verify करने के लिए fastify.inject() उपयोग करें।

import test from 'node:test';
import assert from 'node:assert';
import build from './app.js';

test('GET /health returns 200', async () => {
  const fastify = await build();
  
  const response = await fastify.inject({
    method: 'GET',
    url: '/health',
  });
  
  assert.equal(response.statusCode, 200);
  assert.deepEqual(JSON.parse(response.body), { status: 'ok' });
  
  await fastify.close();
});

inject से testing, बिना network

inject light-my-request से memory में request simulate करता है।

  • कोई port नहीं खुलता।
  • res.statusCode और res.json() से जवाब पढ़ें।
const test = require('node:test');
const assert = require('node:assert');
const Fastify = require('fastify');

test('GET /ping', async () => {
  const app = Fastify();
  app.get('/ping', async () => ({ pong: true }));
  const res = await app.inject({ method: 'GET', url: '/ping' });
  assert.strictEqual(res.statusCode, 200);
  assert.deepStrictEqual(res.json(), { pong: true });
});

त्वरित जाँच

त्वरित जाँच: unit tests में server चलाकर fetch करने की जगह `app.inject()` क्यों बेहतर है?

  • यह तेज़ है और free port नहीं चाहिए
  • यह सारे hooks छोड़ देता है
  • यह सिर्फ़ POST के लिए चलता है
Answer

यह तेज़ है और free port नहीं चाहिए — inject पूरा lifecycle in-process चलाता है, इसलिए hooks और validation लागू रहते हैं।