### Install Supertest Source: https://github.com/forwardemail/supertest/blob/master/README.md Install Supertest as a development dependency using npm. This command saves the package to your package.json file. ```bash npm install supertest --save-dev ``` -------------------------------- ### Promise Support and Async/Await with Supertest Source: https://context7.com/forwardemail/supertest/llms.txt Supertest requests return promises, allowing integration with .then() or async/await syntax. This example demonstrates fetching users and creating a new user using both promise chaining and async/await. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/users', (req, res) => { res.json([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]); }); app.post('/users', express.json(), (req, res) => { res.status(201).json({ id: 3, ...req.body }); }); // Using Promises request(app) .get('/users') .expect(200) .then((res) => { console.log('Users:', res.body); return request(app) .post('/users') .send({ name: 'Bob' }) .expect(201); }) .then((res) => { console.log('Created user:', res.body); }) .catch((err) => { console.error('Test failed:', err); }); // Using async/await with Jest or Mocha describe('Users API', () => { it('fetches users', async () => { const response = await request(app) .get('/users') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); expect(response.body).toHaveLength(2); expect(response.body[0].name).toBe('John'); }); it('creates a user', async () => { const response = await request(app) .post('/users') .send({ name: 'Alice', email: 'alice@example.com' }) .expect(201); expect(response.body.id).toBe(3); expect(response.body.name).toBe('Alice'); }); }); ``` -------------------------------- ### Assert Cookie Exists in Request (Failing Example) Source: https://context7.com/forwardemail/supertest/llms.txt This example demonstrates a failing assertion using `cookies.new()`. It shows that the assertion will fail if the cookie already exists in the request, as `cookies.new()` specifically checks for newly set cookies. ```javascript // This would fail - cookie already exists in request request(app) .get('/first-visit') .set('Cookie', 'newVisitor=true') .expect(cookies.new({ name: 'newVisitor' })) .end((err) => { console.log(err.message); // Expected assertion to fail }); ``` -------------------------------- ### Require Supertest Source: https://github.com/forwardemail/supertest/blob/master/README.md Once installed, Supertest can be referenced in your project by calling require('supertest'). ```javascript require('supertest'); ``` -------------------------------- ### HTTP Method Functions for Testing Source: https://context7.com/forwardemail/supertest/llms.txt Utilize HTTP method functions like `.post()`, `.put()`, and `.delete()` to make requests with specific methods. This example demonstrates testing POST, PUT, and DELETE operations on a '/users' endpoint. ```javascript const request = require('supertest'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.post('/users', (req, res) => { res.status(201).json({ id: 1, ...req.body }); }); app.put('/users/:id', (req, res) => { res.status(200).json({ id: req.params.id, ...req.body }); }); app.delete('/users/:id', (req, res) => { res.sendStatus(204); }); // POST request with JSON body request(app) .post('/users') .send({ name: 'John', email: 'john@example.com' }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(201) .end((err, res) => { if (err) throw err; console.log(res.body); // { id: 1, name: 'John', email: 'john@example.com' } }); // PUT request request(app) .put('/users/1') .send({ name: 'John Updated' }) .expect(200, { id: '1', name: 'John Updated' }) .end((err) => { if (err) throw err; }); // DELETE request request(app) .delete('/users/1') .expect(204) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### Create and Test Express App Request Source: https://context7.com/forwardemail/supertest/llms.txt Use `request(app)` to create a test request for an Express application. Supertest automatically manages server lifecycle. This example tests a GET request to '/users'. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/users', (req, res) => { res.status(200).json([ { id: 1, name: 'John' }, { id: 2, name: 'Jane' } ]); }); // Test with Express app directly request(app) .get('/users') .expect('Content-Type', /json/) .expect(200) .end((err, res) => { if (err) throw err; console.log(res.body); // [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] }); // Test with URL string request('http://localhost:3000') .get('/users') .expect(200) .end((err, res) => { if (err) throw err; }); ``` -------------------------------- ### Test with Mocha and 'done' callback Source: https://github.com/forwardemail/supertest/blob/master/README.md An example using Mocha to test an Express application. It demonstrates passing the 'done' callback directly to `.expect()` for asynchronous test completion. ```javascript describe('GET /user', function() { it('responds with json', function(done) { request(app) .get('/user') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200, done); }); }); ``` -------------------------------- ### Setting cookies on a request Source: https://github.com/forwardemail/supertest/blob/master/README.md Example of manually setting cookies on a request using the set method. ```javascript agent(app) .get('/api/content') .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo']) .send() .expect(200) .end((err, res) => { if (err) { return done(err); } expect(res.text).to.be.equal('hey'); return done(); }); ``` -------------------------------- ### Asserting status and body with Supertest Source: https://github.com/forwardemail/supertest/blob/master/README.md Basic examples of using the expect method to validate response status codes and body content. ```javascript request.get('/').expect(200, function(err){ console.log(err); }); request.get('/').expect('heya', function(err){ console.log(err); }); ``` -------------------------------- ### Core API: request(app) Source: https://context7.com/forwardemail/supertest/llms.txt Creates a new test request object for the given Express app, HTTP server, or URL string. The app is automatically started on an ephemeral port if not already listening. ```APIDOC ## request(app) ### Description Creates a new test request object for the given Express app, HTTP server, or URL string. The app is automatically started on an ephemeral port if not already listening. ### Method `request(app)` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/users', (req, res) => { res.status(200).json([ { id: 1, name: 'John' }, { id: 2, name: 'Jane' } ]); }); // Test with Express app directly request(app) .get('/users') .expect('Content-Type', /json/) .expect(200) .end((err, res) => { if (err) throw err; console.log(res.body); }); // Test with URL string request('http://localhost:3000') .get('/users') .expect(200) .end((err, res) => { if (err) throw err; }); ``` ### Response #### Success Response (200) Returns the result of the HTTP request. #### Response Example ```json [ { "id": 1, "name": "John" }, { "id": 2, "name": "Jane" } ] ``` ``` -------------------------------- ### Basic Request and Response Test Source: https://github.com/forwardemail/supertest/blob/master/README.md Demonstrates a basic test case for an Express application without a testing framework. It sends a GET request and asserts the content type, length, and status code. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/user', function(req, res) { res.status(200).json({ name: 'john' }); }); request(app) .get('/user') .expect('Content-Type', /json/) .expect('Content-Length', '15') .expect(200) .end(function(err, res) { if (err) throw err; }); ``` -------------------------------- ### Modifying Response Before Assertion Source: https://github.com/forwardemail/supertest/blob/master/README.md An example demonstrating how to modify the response body or headers before an assertion is executed by using a callback function within `.expect()`. ```javascript describe('POST /user', function() { it('user.name should be an case-insensitive match for "john"', function(done) { request(app) .post('/user') .send('name=john') // x-www-form-urlencoded upload .set('Accept', 'application/json') .expect(function(res) { res.body.id = 'some fixed id'; res.body.name = res.body.name.toLowerCase(); }) .expect(200, { id: 'some fixed id', name: 'john' }, done); }); }); ``` -------------------------------- ### HTTP Basic Authentication Source: https://github.com/forwardemail/supertest/blob/master/README.md Illustrates how to use the `.auth()` method to pass HTTP username and password for basic authentication, similar to Superagent. ```javascript describe('GET /user', function() { it('responds with json', function(done) { request(app) .get('/user') .auth('username', 'password') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200, done); }); }); ``` -------------------------------- ### Testing with Async/Await Source: https://github.com/forwardemail/supertest/blob/master/README.md Shows how to use the async/await syntax for cleaner asynchronous testing with Supertest. Assertions are made directly on the awaited response object. ```javascript describe('GET /users', function() { it('responds with json', async function() { const response = await request(app) .get('/users') .set('Accept', 'application/json') expect(response.headers["content-type"]).toMatch(/json/); expect(response.status).toEqual(200); expect(response.body.email).toEqual('foo@bar.com'); }); }); ``` -------------------------------- ### Enable HTTP/2 Support Source: https://context7.com/forwardemail/supertest/llms.txt Enables the HTTP/2 protocol via options, agent configuration, or existing server instances. ```javascript const request = require('supertest'); const app = function(req, res) { res.end('HTTP/2 response'); }; // Enable HTTP/2 via options request(app, { http2: true }) .get('/') .expect(200) .expect('HTTP/2 response') .end((err) => { if (err) throw err; }); // Enable HTTP/2 on agent request.agent(app, { http2: true }) .get('/') .expect(200) .end((err) => { if (err) throw err; }); // Enable HTTP/2 on existing server const http2 = require('http2'); const server = http2.createServer(app); server.listen(() => { request(server) .get('/') .http2() .expect(200) .end((err) => { if (err) throw err; server.close(); }); }); ``` -------------------------------- ### Enable HTTP2 Protocol Source: https://github.com/forwardemail/supertest/blob/master/README.md Shows how to enable the HTTP2 protocol for requests made with Supertest by passing an options object to the request or request.agent function. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/user', function(req, res) { res.status(200).json({ name: 'john' }); }); request(app, { http2: true }) .get('/user') .expect('Content-Type', /json/) .expect('Content-Length', '15') .expect(200) .end(function(err, res) { if (err) throw err; }); request.agent(app, { http2: true }) .get('/user') .expect('Content-Type', /json/) .expect('Content-Length', '15') .expect(200) .end(function(err, res) { if (err) throw err; }); ``` -------------------------------- ### Testing with Promises Source: https://github.com/forwardemail/supertest/blob/master/README.md Demonstrates how to use Promises for asynchronous testing with Supertest. The test passes if the promise resolves, and fails if it rejects or an assertion fails. ```javascript describe('GET /users', function() { it('responds with json', function() { return request(app) .get('/users') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then(response => { expect(response.body.email).toEqual('foo@bar.com'); }) }); }); ``` -------------------------------- ### Multipart File Uploads Source: https://github.com/forwardemail/supertest/blob/master/README.md Illustrates how to perform multipart file uploads using Supertest, including sending form fields and attaching files. ```javascript request(app) .post('/') .field('name', 'my awesome avatar') .field('complex_object', '{"attribute": "value"}', {contentType: 'application/json'}) .attach('avatar', 'test/fixtures/avatar.jpg') ... ``` -------------------------------- ### Configure Redirect Handling with .redirects(n) Source: https://context7.com/forwardemail/supertest/llms.txt Controls the maximum number of redirects to follow. Defaults to 0, meaning no redirects are followed. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/old-page', (req, res) => { res.redirect('/new-page'); }); app.get('/new-page', (req, res) => { res.redirect('/final-page'); }); app.get('/final-page', (req, res) => { res.send('Final destination'); }); // Default: no redirects followed (returns 302) request(app) .get('/old-page') .expect(302) .expect('Location', '/new-page') .end((err) => { if (err) throw err; }); // Follow one redirect request(app) .get('/old-page') .redirects(1) .expect(302) .end((err, res) => { if (err) throw err; console.log(res.headers.location); // '/final-page' }); // Follow all redirects request(app) .get('/old-page') .redirects(2) .expect(200) .expect('Final destination') .end((err) => { if (err) throw err; }); ``` -------------------------------- ### HTTP/2 Support Source: https://context7.com/forwardemail/supertest/llms.txt Enables HTTP/2 protocol for requests. ```APIDOC ## HTTP/2 Support ### Description Enable HTTP/2 protocol for requests by passing { http2: true } option or calling .http2(). ``` -------------------------------- ### Set HTTP Basic Authentication with .auth() Source: https://context7.com/forwardemail/supertest/llms.txt Configures Basic Authentication credentials for the request. Requires an Express app or server instance to validate the Authorization header. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/admin', (req, res) => { const auth = req.get('Authorization'); const expected = 'Basic ' + Buffer.from('admin:secret').toString('base64'); if (auth === expected) { res.json({ message: 'Welcome admin' }); } else { res.status(401).json({ error: 'Unauthorized' }); } }); // Using .auth() for Basic Authentication request(app) .get('/admin') .auth('admin', 'secret') .expect(200) .expect({ message: 'Welcome admin' }) .end((err) => { if (err) throw err; }); // Failed authentication request(app) .get('/admin') .auth('admin', 'wrong-password') .expect(401) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### .redirects(n) Source: https://context7.com/forwardemail/supertest/llms.txt Sets the maximum number of redirects to follow for a request. ```APIDOC ## .redirects(n) ### Description Sets the maximum number of redirects to follow. Default is 0 (no redirects followed). ### Parameters - **n** (number) - Required - The maximum number of redirects to follow. ``` -------------------------------- ### Promise Support and Async/Await Source: https://context7.com/forwardemail/supertest/llms.txt Supertest requests return promises, which can be used with `.then()` or async/await syntax. This allows for cleaner asynchronous test flows without needing to explicitly call `.end()` on every request. ```APIDOC ## Promise Support and Async/Await Supertest requests return promises, enabling use with `.then()` or async/await syntax without calling `.end()`. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/users', (req, res) => { res.json([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]); }); app.post('/users', express.json(), (req, res) => { res.status(201).json({ id: 3, ...req.body }); }); // Using Promises request(app) .get('/users') .expect(200) .then((res) => { console.log('Users:', res.body); return request(app) .post('/users') .send({ name: 'Bob' }) .expect(201); }) .then((res) => { console.log('Created user:', res.body); }) .catch((err) => { console.error('Test failed:', err); }); // Using async/await with Jest or Mocha describe('Users API', () => { it('fetches users', async () => { const response = await request(app) .get('/users') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); expect(response.body).toHaveLength(2); expect(response.body[0].name).toBe('John'); }); it('creates a user', async () => { const response = await request(app) .post('/users') .send({ name: 'Alice', email: 'alice@example.com' }) .expect(201); expect(response.body.id).toBe(3); expect(response.body.name).toBe('Alice'); }); }); ``` ``` -------------------------------- ### Persisting cookies with request.agent Source: https://github.com/forwardemail/supertest/blob/master/README.md Demonstrates how to use request.agent to maintain cookie state across multiple requests in a Mocha test suite. ```javascript const request = require('supertest'); const should = require('should'); const express = require('express'); const cookieParser = require('cookie-parser'); describe('request.agent(app)', function() { const app = express(); app.use(cookieParser()); app.get('/', function(req, res) { res.cookie('cookie', 'hey'); res.send(); }); app.get('/return', function(req, res) { if (req.cookies.cookie) res.send(req.cookies.cookie); else res.send(':(') }); const agent = request.agent(app); it('should save cookies', function(done) { agent .get('/') .expect('set-cookie', 'cookie=hey; Path=/', done); }); it('should send cookies', function(done) { agent .get('/return') .expect('hey', done); }); }); ``` -------------------------------- ### Persistent Sessions with request.agent() Source: https://context7.com/forwardemail/supertest/llms.txt Use request.agent(app) to create a persistent agent that maintains cookies across requests. This is essential for testing authenticated sessions. ```javascript const request = require('supertest'); const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); app.use(cookieParser()); app.post('/login', (req, res) => { res.cookie('session', 'abc123', { httpOnly: true }); res.json({ message: 'Logged in' }); }); app.get('/profile', (req, res) => { if (req.cookies.session === 'abc123') { res.json({ name: 'John', email: 'john@example.com' }); } else { res.status(401).json({ error: 'Unauthorized' }); } }); app.post('/logout', (req, res) => { res.clearCookie('session'); res.json({ message: 'Logged out' }); }); // Create persistent agent const agent = request.agent(app); // Login - cookie will be saved agent .post('/login') .expect('set-cookie', /session/) .expect(200) .end((err) => { if (err) throw err; // Cookie is automatically sent with subsequent requests agent .get('/profile') .expect(200) .end((err, res) => { if (err) throw err; console.log('Profile:', res.body); // { name: 'John', email: 'john@example.com' } // Logout agent .post('/logout') .expect(200) .end((err) => { if (err) throw err; }); }); }); // Set default headers on agent const authenticatedAgent = request.agent(app) .set('Authorization', 'Bearer token123') .set('X-Custom-Header', 'value'); ``` -------------------------------- ### Cookie assertion patterns Source: https://github.com/forwardemail/supertest/blob/master/README.md Demonstrates using cookie assertions to verify cookie attributes like domain, path, and httpOnly status. ```javascript // setup super-test const request = require('supertest'); const express = require('express'); const cookies = request.cookies; // setup express test service const app = express(); app.get('/users', function(req, res) { res.cookie('alpha', 'one', { domain: 'domain.com', path: '/', httpOnly: true }); res.send(200, { name: 'tobi' }); }); // test request to service request(app) .get('/users') .expect('Content-Type', /json/) .expect('Content-Length', '15') .expect(200) // assert 'alpha' cookie is set with domain, path, and httpOnly options .expect(cookies.set({ name: 'alpha', options: ['domain', 'path', 'httponly'] })) // assert 'bravo' cookie is NOT set .expect(cookies.not('set', { name: 'bravo' })) .end(function(err, res) { if (err) { throw err; } }); ``` -------------------------------- ### Execute requests with .end() Source: https://context7.com/forwardemail/supertest/llms.txt Finalizes the request and provides a callback to handle the response or errors. The server is automatically closed after completion. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/data', (req, res) => { res.json({ success: true, data: [1, 2, 3] }); }); // Basic usage with error handling request(app) .get('/data') .expect(200) .end((err, res) => { if (err) { console.error('Test failed:', err.message); return; } console.log('Response body:', res.body); console.log('Response status:', res.status); console.log('Response headers:', res.headers); }); // Using with Mocha describe('GET /data', function() { it('returns data array', function(done) { request(app) .get('/data') .expect(200) .end((err, res) => { if (err) return done(err); if (!Array.isArray(res.body.data)) { return done(new Error('data should be an array')); } done(); }); }); }); ``` -------------------------------- ### Handle Multipart Form Data with .attach() and .field() Source: https://context7.com/forwardemail/supertest/llms.txt Manages multipart/form-data requests for file uploads and form fields. Requires middleware like multer on the server side to process the incoming data. ```javascript const request = require('supertest'); const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('avatar'), (req, res) => { res.json({ file: req.file, name: req.body.name, description: req.body.description }); }); // Upload file with additional fields request(app) .post('/upload') .field('name', 'my-avatar') .field('description', 'Profile picture') .attach('avatar', 'test/fixtures/avatar.jpg') .expect(200) .end((err, res) => { if (err) throw err; console.log('Uploaded:', res.body.file.filename); }); // Send complex object as field request(app) .post('/upload') .field('name', 'document') .field('metadata', JSON.stringify({ type: 'pdf', pages: 10 }), { contentType: 'application/json' }) .attach('file', 'test/fixtures/document.pdf') .expect(200) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### Re-assigning Request Variable for Same Host Source: https://github.com/forwardemail/supertest/blob/master/README.md Shows how to re-assign the request variable to a specific host URL, avoiding the need to pass the app or URL on subsequent requests to the same host. ```javascript request = request('http://localhost:5555'); ``` -------------------------------- ### Set Request Timeouts with .timeout(ms) Source: https://context7.com/forwardemail/supertest/llms.txt Defines the maximum duration in milliseconds for a request to complete. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/slow', (req, res) => { setTimeout(() => { res.json({ data: 'delayed response' }); }, 5000); }); app.get('/fast', (req, res) => { res.json({ data: 'quick response' }); }); // Request that will timeout request(app) .get('/slow') .timeout(1000) // 1 second timeout .expect(200) .end((err, res) => { if (err) { console.log('Request timed out:', err.message); } }); // Fast request with timeout request(app) .get('/fast') .timeout(5000) .expect(200) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### .end(fn) Source: https://context7.com/forwardemail/supertest/llms.txt Performs the request and invokes the callback with (err, res). ```APIDOC ## .end(fn) ### Description Performs the request and invokes the callback with (err, res). The server is automatically closed after the request completes. ### Parameters - **fn** (function) - Required - Callback function with signature (err, res). ``` -------------------------------- ### Set Custom Host Header with agent.host(hostname) Source: https://context7.com/forwardemail/supertest/llms.txt Configures a specific host header for requests routed through the agent. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/', (req, res) => { res.json({ hostname: req.hostname }); }); const agent = request.agent(app); agent .host('custom.example.com') .get('/') .expect(200) .end((err, res) => { if (err) throw err; console.log(res.body.hostname); // 'custom.example.com' }); ``` -------------------------------- ### .expect(body[, fn]) Source: https://context7.com/forwardemail/supertest/llms.txt Asserts the response body using string comparison, regular expressions, or deep equality for JSON objects. ```APIDOC ## .expect(body[, fn]) ### Description Asserts the response body. Supports string comparison, regular expressions, and parsed JSON object comparison using deep equality. ### Parameters - **body** (string|regexp|object) - Required - The expected body content to match against the response. ``` -------------------------------- ### Setting Bearer Token with .bearer() Source: https://context7.com/forwardemail/supertest/llms.txt The .bearer(token) method is a convenient shortcut for setting the 'Authorization' header with a 'Bearer' token. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/protected', (req, res) => { const authHeader = req.get('Authorization'); if (authHeader === 'Bearer valid-token') { res.json({ data: 'secret data' }); } else { res.status(401).json({ error: 'Invalid token' }); } }); // Using .bearer() shortcut request(app) .get('/protected') .bearer('valid-token') .expect(200) .expect({ data: 'secret data' }) .end((err) => { if (err) throw err; }); // Equivalent to: request(app) .get('/protected') .set('Authorization', 'Bearer valid-token') .expect(200) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### Add Query Parameters with .query() Source: https://context7.com/forwardemail/supertest/llms.txt Appends query string parameters to the request URL. Handles objects, arrays, and nested structures. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/search', (req, res) => { res.json({ query: req.query.q, page: req.query.page, limit: req.query.limit, filters: req.query.filters }); }); // Add query parameters request(app) .get('/search') .query({ q: 'supertest', page: 1, limit: 10 }) .expect(200) .end((err, res) => { if (err) throw err; console.log(res.body); // { query: 'supertest', page: '1', limit: '10' } }); // Array query parameters request(app) .get('/search') .query({ 'filters[]': ['active', 'featured'] }) .expect(200) .end((err, res) => { if (err) throw err; console.log(res.body.filters); // ['active', 'featured'] }); // Object query parameters request(app) .get('/search') .query({ filters: { status: 'active', type: 'premium' } }) .expect(200) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### request.agent(app) Source: https://context7.com/forwardemail/supertest/llms.txt Creates a persistent agent that maintains cookies across requests. This is particularly useful for testing authenticated sessions where cookies need to be preserved between different API calls. ```APIDOC ## request.agent(app) Creates a persistent agent that maintains cookies across requests, useful for testing authenticated sessions. ```javascript const request = require('supertest'); const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); app.use(cookieParser()); app.post('/login', (req, res) => { res.cookie('session', 'abc123', { httpOnly: true }); res.json({ message: 'Logged in' }); }); app.get('/profile', (req, res) => { if (req.cookies.session === 'abc123') { res.json({ name: 'John', email: 'john@example.com' }); } else { res.status(401).json({ error: 'Unauthorized' }); } }); app.post('/logout', (req, res) => { res.clearCookie('session'); res.json({ message: 'Logged out' }); }); // Create persistent agent const agent = request.agent(app); // Login - cookie will be saved agent .post('/login') .expect('set-cookie', /session/) .expect(200) .end((err) => { if (err) throw err; // Cookie is automatically sent with subsequent requests agent .get('/profile') .expect(200) .end((err, res) => { if (err) throw err; console.log('Profile:', res.body); // { name: 'John', email: 'john@example.com' } // Logout agent .post('/logout') .expect(200) .end((err) => { if (err) throw err; }); }); }); // Set default headers on agent const authenticatedAgent = request.agent(app) .set('Authorization', 'Bearer token123') .set('X-Custom-Header', 'value'); ``` ``` -------------------------------- ### .bearer(token) Source: https://context7.com/forwardemail/supertest/llms.txt A shortcut method for setting the `Authorization` header with a Bearer token. It simplifies the process of adding authentication tokens to requests. ```APIDOC ## .bearer(token) Shortcut method to set the Authorization header with a Bearer token. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/protected', (req, res) => { const authHeader = req.get('Authorization'); if (authHeader === 'Bearer valid-token') { res.json({ data: 'secret data' }); } else { res.status(401).json({ error: 'Invalid token' }); } }); // Using .bearer() shortcut request(app) .get('/protected') .bearer('valid-token') .expect(200) .expect({ data: 'secret data' }) .end((err) => { if (err) throw err; }); // Equivalent to: request(app) .get('/protected') .set('Authorization', 'Bearer valid-token') .expect(200) .end((err) => { if (err) throw err; }); ``` ``` -------------------------------- ### .expect(field, value[, fn]) Source: https://context7.com/forwardemail/supertest/llms.txt Asserts response header field values using exact string matching, numeric values, or regular expressions. ```APIDOC ## .expect(field, value[, fn]) ### Description Asserts response header field values. Supports exact string matching, numeric values, and regular expressions. ### Parameters - **field** (string) - Required - The header field name. - **value** (string|number|regexp) - Required - The expected value for the header field. ``` -------------------------------- ### Basic Authentication API Source: https://context7.com/forwardemail/supertest/llms.txt Sets HTTP Basic Authentication credentials for requests. This is useful for testing endpoints that require authentication. ```APIDOC ## POST /admin ### Description Tests an endpoint that requires HTTP Basic Authentication. ### Method GET ### Endpoint /admin ### Parameters #### Query Parameters - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. ### Request Example ```javascript request(app) .get('/admin') .auth('admin', 'secret') .expect(200) .expect({ message: 'Welcome admin' }) .end((err) => { if (err) throw err; }); ``` ### Response #### Success Response (200) - **message** (string) - A welcome message for authenticated users. #### Response Example ```json { "message": "Welcome admin" } ``` #### Error Response (401) - **error** (string) - An error message indicating unauthorized access. #### Response Example ```json { "error": "Unauthorized" } ``` ``` -------------------------------- ### Assert Cookies with cookies.set(expects) Source: https://context7.com/forwardemail/supertest/llms.txt Verifies that specific cookies are present in the response, optionally checking for specific attributes. ```javascript const request = require('supertest'); const express = require('express'); const cookies = request.cookies; const app = express(); app.get('/login', (req, res) => { res.cookie('session', 'abc123', { domain: 'example.com', path: '/', httpOnly: true, secure: true, expires: new Date(Date.now() + 86400000) }); res.json({ loggedIn: true }); }); // Assert cookie is set with specific options request(app) .get('/login') .expect(200) .expect(cookies.set({ name: 'session', options: ['domain', 'path', 'httponly', 'secure', 'expires'] })) .end((err) => { if (err) throw err; }); // Assert multiple cookies request(app) .get('/login') .expect(cookies.set([ { name: 'session', options: ['httponly'] }, { name: 'preferences', options: ['path'] } ])) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### Assert New Cookie Set Source: https://context7.com/forwardemail/supertest/llms.txt Use `cookies.new()` to assert that a cookie is set in the response but was not present in the request. This is ideal for verifying first-visit cookies or newly created session identifiers. ```javascript const request = require('supertest'); const express = require('express'); const cookies = request.cookies; const app = express(); app.get('/first-visit', (req, res) => { res.cookie('newVisitor', 'true', { path: '/' }); res.send('Welcome!'); }); // Assert cookie is newly set (not in request) request(app) .get('/first-visit') .expect(cookies.new({ name: 'newVisitor' })) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### agent.host(hostname) Source: https://context7.com/forwardemail/supertest/llms.txt Sets a custom host header for requests made through the agent. ```APIDOC ## agent.host(hostname) ### Description Sets a custom host header for requests made through the agent. ### Parameters - **hostname** (string) - Required - The hostname to set in the header. ``` -------------------------------- ### Assert response headers with .expect() Source: https://context7.com/forwardemail/supertest/llms.txt Validates response header fields using exact strings, regular expressions, or numeric values. ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/api/data', (req, res) => { res.set('X-Custom-Header', 'custom-value'); res.set('X-Request-Id', '12345'); res.json({ data: 'test' }); }); // Assert exact header value request(app) .get('/api/data') .expect('X-Custom-Header', 'custom-value') .expect('Content-Type', 'application/json; charset=utf-8') .end((err) => { if (err) throw err; }); // Assert header with regular expression request(app) .get('/api/data') .expect('Content-Type', /json/) .end((err) => { if (err) throw err; }); // Assert numeric header value request(app) .get('/api/data') .expect('X-Request-Id', '12345') .end((err) => { if (err) throw err; }); // Chain multiple header assertions request(app) .get('/api/data') .expect('Content-Type', /json/) .expect('X-Custom-Header', 'custom-value') .expect(200) .end((err) => { if (err) throw err; }); ``` -------------------------------- ### Basic Assertions Source: https://github.com/forwardemail/supertest/blob/master/README.md SuperTest allows for various assertions on the response, including status codes, response bodies, and headers. ```APIDOC ## GET / ### Description Performs a GET request to the root path and asserts the response status code. ### Method GET ### Endpoint / ### Parameters ### Request Example ```javascript request.get('/').expect(200, function(err){ console.log(err); }); ``` ### Response #### Success Response (200) - **body** (any) - The response body. #### Response Example ```json { "example": "response body" } ``` ## GET / ### Description Performs a GET request to the root path and asserts the response body with a string. ### Method GET ### Endpoint / ### Parameters ### Request Example ```javascript request.get('/').expect('heya', function(err){ console.log(err); }); ``` ### Response #### Success Response (200) - **body** (string) - The response body. #### Response Example ```json { "example": "response body" } ``` ## GET / ### Description Performs a GET request to the root path and asserts a specific header field and its value. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **field** (string) - Required - The header field to assert. - **value** (string) - Required - The expected value of the header field. ### Request Example ```javascript request(app) .get('/users') .expect('Content-Type', /json/) .expect('Content-Length', '15') .end(function(err, res) { if (err) throw err; }); ``` ### Response #### Success Response (200) - **body** (any) - The response body. #### Response Example ```json { "example": "response body" } ``` ## POST /api/content ### Description Performs a POST request to the /api/content endpoint, setting cookies and asserting the response. ### Method POST ### Endpoint /api/content ### Parameters ### Request Body - **body** (any) - The request body. ### Request Example ```javascript agent(app) .get('/api/content') .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo']) .send() .expect(200) .end((err, res) => { if (err) { return done(err); } expect(res.text).to.be.equal('hey'); return done(); }); ``` ### Response #### Success Response (200) - **text** (string) - The response text. #### Response Example ```json { "example": "hey" } ``` ## GET / ### Description Performs a GET request and passes a custom assertion function to check the response body. ### Method GET ### Endpoint / ### Parameters ### Request Example ```javascript request(app) .get('/') .expect(hasPreviousAndNextKeys) .end(done); function hasPreviousAndNextKeys(res) { if (!('next' in res.body)) throw new Error("missing next key"); if (!('prev' in res.body)) throw new Error("missing prev key"); } ``` ### Response #### Success Response (200) - **body** (object) - The response body, expected to have 'next' and 'prev' keys. #### Response Example ```json { "example": "response body" } ``` ## GET / ### Description Performs a GET request and invokes a callback function with the error and response objects. ### Method GET ### Endpoint / ### Parameters ### Request Example ```javascript request(app).get('/').end(function(err, res) { if (err) { throw err; } }); ``` ### Response #### Success Response (200) - **res** (object) - The response object. #### Response Example ```json { "example": "response object" } ``` ``` -------------------------------- ### .timeout(ms) Source: https://context7.com/forwardemail/supertest/llms.txt Sets the request timeout in milliseconds. ```APIDOC ## .timeout(ms) ### Description Sets request timeout in milliseconds. ### Parameters - **ms** (number) - Required - Timeout duration in milliseconds. ``` -------------------------------- ### Response Assertion: .expect(status, body[, fn]) Source: https://context7.com/forwardemail/supertest/llms.txt Asserts both the response status code and body in a single call. ```APIDOC ## .expect(status, body[, fn]) ### Description Asserts both the response status code and body in a single call. ### Method `.expect(status, body[, fn])` ### Endpoint N/A (Assertion method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const request = require('supertest'); const express = require('express'); const app = express(); app.get('/user', (req, res) => { res.status(200).json({ name: 'john', email: 'john@example.com' }); }); app.get('/message', (req, res) => { res.status(200).send('Hello World'); }); // Assert status and JSON body request(app) .get('/user') .expect(200, { name: 'john', email: 'john@example.com' }) .end((err) => { if (err) throw err; }); // Assert status and text body request(app) .get('/message') .expect(200, 'Hello World') .end((err) => { if (err) throw err; }); ``` ### Response #### Success Response (200) Indicates that both the status code and body assertions passed. #### Response Example N/A (This is an assertion method, not a response handler) ```