What is @hapi/shot?
@hapi/shot is a Node.js library used for testing HTTP servers. It allows you to inject requests into a server and inspect the responses, making it useful for unit testing server-side code without the need to actually start the server.
Injecting Requests
This feature allows you to inject HTTP requests into a server and inspect the responses. The example demonstrates how to create a simple HTTP server and use Shot to inject a GET request, then log the status code and payload of the response.
const Shot = require('@hapi/shot');
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world!');
});
Shot.inject(server, { method: 'get', url: '/' }, (res) => {
console.log(res.statusCode); // 200
console.log(res.payload); // 'Hello, world!'
});
Testing with Assertions
This feature allows you to perform assertions on the responses to ensure they meet expected criteria. The example shows how to create a server that responds with JSON and use Shot to inject a GET request, then assert the status code, content type, and payload.
const Shot = require('@hapi/shot');
const http = require('http');
const assert = require('assert');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello, world!' }));
});
Shot.inject(server, { method: 'get', url: '/' }, (res) => {
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.headers['content-type'], 'application/json');
assert.deepStrictEqual(JSON.parse(res.payload), { message: 'Hello, world!' });
console.log('All assertions passed');
});