Testing

Integration tests and service fixtures

Integration tests exercise connected components. An HTTP integration test can send a real request to a local server and verify the status, headers and body rather than merely calling the route function. Bind to 127.0.0.1 and port 0 so the OS chooses a free port; wait for listening before issuing requests. Use timeouts, synthetic data and explicit teardown. In-process framework injection avoids real sockets, while Supertest or a real client may exercise a different boundary. Verify both successful and rejected requests. Database integration requires a real appropriate provider; a mock repository cannot establish SQL semantics. Do not use a fixed port that may belong to another application, or point tests at a production service. An HTTP 200 without a body assertion misses contract regressions. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/http.html.

Formal Syntax & Structure

nodejs syntaxnodejs
http.createServer(listener); server.listen(0, "127.0.0.1"); server.close(callback)

Working Example

Example Snippetnodejs
import {createServer} from 'node:http';import {once} from 'node:events';import assert from 'node:assert/strict';const server=createServer((req,res)=>{res.setHeader('content-type','application/json');if(req.url==='/items/7')res.end(JSON.stringify({id:7}));else{res.statusCode=404;res.end(JSON.stringify({error:'not_found'}));}});server.listen(0,'127.0.0.1');await once(server,'listening');try{for(const [path,status,body] of [['/items/7',200,{id:7}],['/items/8',404,{error:'not_found'}]]){const r=await fetch(`http://127.0.0.1:${server.address().port}${path}`,{signal:AbortSignal.timeout(1000)});assert.equal(r.status,status);assert.equal(r.headers.get('content-type'),'application/json');assert.deepEqual(await r.json(),body);console.log(status);}}finally{await new Promise((ok,fail)=>server.close(e=>e?fail(e):ok()));}
Node.js Reference