### Per-Test Configuration with setup() Source: https://context7.com/vlucas/frisby/llms.txt Configures settings for a specific test chain, allowing for per-test overrides or additions to existing settings. The `setup` method can merge with or replace existing configurations. ```javascript const frisby = require('frisby'); it('should use per-test setup', function () { return frisby.setup({ request: { headers: { 'Authorization': 'Bearer test-token' } } }) .get('https://api.example.com/users/1') .expect('status', 200); }); it('should merge multiple setup calls', function () { return frisby.setup({ request: { headers: { 'One': 'one' } } }) .setup({ request: { headers: { 'Two': 'two' } } }) .get('https://api.example.com/two-headers') .expect('status', 200); }); it('should replace setup with second parameter', function () { return frisby.setup({ request: { headers: { 'WrongHeader': 'value' } } }) .setup({ request: { headers: { 'Authorization': 'Basic Auth' } } }, true) // true = replace instead of merge .get('https://api.example.com/users/1/auth') .expect('status', 200); }); ``` -------------------------------- ### Install Frisby dependencies Source: https://context7.com/vlucas/frisby/llms.txt Install the required packages via NPM. ```bash npm install --save-dev frisby joi jest ``` -------------------------------- ### Basic HTTP GET Request Test Source: https://github.com/vlucas/frisby/blob/master/README.md A minimal example to test an HTTP GET request and assert its status code. Ensure Frisby is imported. ```javascript const frisby = require('frisby'); it('should be a teapot', function () { // Return the Frisby.js Spec in the 'it()' (just like a promise) return frisby.get('http://httpbin.org/status/418') .expect('status', 418); }); ``` -------------------------------- ### Apply reusable configuration with use() Source: https://context7.com/vlucas/frisby/llms.txt Use a setup function to modify the FrisbySpec, ideal for shared authentication or configuration logic. ```javascript const frisby = require('frisby'); // Create reusable helper const withAuthHeader = function (spec) { spec.setup({ request: { headers: { 'Authorization': 'Basic Auth' } } }); }; it('should apply configuration via use()', function () { return frisby.use(withAuthHeader) .get('https://api.example.com/users/1/auth') .expect('status', 200); }); ``` -------------------------------- ### Per-Test Configuration - setup() Source: https://context7.com/vlucas/frisby/llms.txt Configures settings for a specific test chain, allowing merging with or replacement of existing settings. ```APIDOC ## setup() - Per-Test Configuration ### Description Configures settings for a specific test chain. Can merge with or replace existing settings. ### Method `frisby.setup(options, [replace])` ### Parameters - **options** (object) - Required - An object containing configuration settings to apply. - **replace** (boolean) - Optional - If true, replaces existing settings instead of merging. ### Request Example (Merge) ```javascript const frisby = require('frisby'); it('should use per-test setup', function () { return frisby.setup({ request: { headers: { 'Authorization': 'Bearer test-token' } } }) .get('https://api.example.com/users/1') .expect('status', 200); }); ``` ### Request Example (Merge Multiple) ```javascript frisby.setup({ request: { headers: { 'One': 'one' } } }) .setup({ request: { headers: { 'Two': 'two' } } }) .get('https://api.example.com/two-headers') .expect('status', 200); ``` ### Request Example (Replace) ```javascript frisby.setup({ request: { headers: { 'WrongHeader': 'value' } } }) .setup({ request: { headers: { 'Authorization': 'Basic Auth' } } }, true) // true = replace instead of merge .get('https://api.example.com/users/1/auth') .expect('status', 200); ``` ``` -------------------------------- ### Perform GET request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP GET request and validates the response status and JSON content. ```javascript const frisby = require('frisby'); it('should get a user by ID', function () { return frisby.get('https://api.example.com/users/1') .expect('status', 200) .expect('json', { id: 1, email: 'joe.schmoe@example.com' }); }); ``` -------------------------------- ### Configure Global Setup Source: https://context7.com/vlucas/frisby/llms.txt Configures default settings for all Frisby tests, including request defaults, headers, timeout, and inspection behavior. This is useful for setting common configurations across your test suite. ```javascript const frisby = require('frisby'); // Configure global defaults frisby.globalSetup({ request: { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer default-token' }, timeout: 10000, inspectOnFailure: true, rawBody: false } }); it('should use global setup', function () { return frisby.get('https://api.example.com/users/1') .expect('status', 200); }); ``` -------------------------------- ### GET Request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP GET request to the specified URL and returns a chainable FrisbySpec object. ```APIDOC ## GET [URL] ### Description Makes an HTTP GET request to the specified URL. ### Method GET ### Request Example frisby.get('https://api.example.com/users/1') ### Response #### Success Response (200) - **id** (number) - User ID - **email** (string) - User email ``` -------------------------------- ### Handle Raw Binary Response Source: https://context7.com/vlucas/frisby/llms.txt Handle binary file responses by enabling `rawBody` mode in Frisby setup. This allows direct access to the response body as an `ArrayBuffer` and is useful for verifying file integrity, such as checking PNG headers. ```javascript const frisby = require('frisby'); it('should handle binary response', function () { return frisby.setup({ request: { rawBody: true } }) .get('https://api.example.com/files/logo.png') .expect('status', 200) .expect('header', 'Content-Type', 'image/png') .then(res => { expect(res.json).toBeUndefined(); expect(res.body).toBeInstanceOf(ArrayBuffer); expect(res.body.byteLength).toBeGreaterThan(8); // Check PNG header const PNG_HEADER = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; expect(new Uint8Array(res.body.slice(0, 8))).toEqual(new Uint8Array(PNG_HEADER)); }); }); ``` -------------------------------- ### Global Configuration - globalSetup() Source: https://context7.com/vlucas/frisby/llms.txt Configures default settings for all Frisby tests, including request defaults, headers, and timeouts. ```APIDOC ## globalSetup() ### Description Configures default settings for all Frisby tests. Settings include request defaults, headers, timeout, and inspection behavior. ### Method `frisby.globalSetup(options)` ### Parameters - **options** (object) - Required - An object containing configuration settings. - **request** (object) - Optional - Default request options. - **headers** (object) - Optional - Default headers. - **timeout** (number) - Optional - Default timeout in milliseconds. - **inspectOnFailure** (boolean) - Optional - Whether to inspect on failure. - **rawBody** (boolean) - Optional - Whether to use raw body. ### Request Example ```javascript const frisby = require('frisby'); frisby.globalSetup({ request: { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer default-token' }, timeout: 10000, inspectOnFailure: true, rawBody: false } }); it('should use global setup', function () { return frisby.get('https://api.example.com/users/1') .expect('status', 200); }); ``` ``` -------------------------------- ### Global Configuration - baseUrl() Source: https://context7.com/vlucas/frisby/llms.txt Sets a global base URL for all subsequent requests, allowing the use of relative paths. ```APIDOC ## baseUrl() ### Description Sets a global base URL for all subsequent requests, allowing you to use relative paths. ### Method `frisby.baseUrl(url)` ### Parameters - **url** (string) - Required - The base URL to set. ### Request Example ```javascript const frisby = require('frisby'); frisby.baseUrl('https://api.example.com'); it('should use relative URL with base', function () { return frisby.fetch('/users/1') .expect('status', 200); }); ``` ``` -------------------------------- ### Run Frisby tests via CLI Source: https://github.com/vlucas/frisby/blob/master/README.md Execute tests by navigating to the project root and running the jest command. ```bash cd your/project jest ``` -------------------------------- ### fetch() Method Source: https://context7.com/vlucas/frisby/llms.txt Low-level fetch method that provides full control over request parameters. ```APIDOC ## [CUSTOM_METHOD] [URL] ### Description Low-level fetch method for custom request configurations. ### Method Custom (e.g., GET, POST) ### Request Body - **options** (object) - Custom headers and request settings ### Request Example frisby.fetch('https://api.example.com/users/1', { method: 'GET', headers: { 'Authorization': 'Bearer token123' } }) ### Response #### Success Response (200) ``` -------------------------------- ### Perform OPTIONS request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP OPTIONS request to check allowed methods and CORS headers. ```javascript const frisby = require('frisby'); it('should return allowed methods', function () { return frisby.options('https://api.example.com/') .expect('status', 204) .expect('header', 'Access-Control-Allow-Methods', /GET/) .expect('header', 'Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); }); ``` -------------------------------- ### Perform fetch() request Source: https://context7.com/vlucas/frisby/llms.txt Provides full control over request parameters, including custom headers and URL encoding options. ```javascript const frisby = require('frisby'); it('should fetch with custom options', function () { return frisby.fetch('https://api.example.com/users/1', { method: 'GET', headers: { 'Authorization': 'Bearer token123' } }) .expect('status', 200); }); // Disable URL encoding when needed it('should fetch without URL encoding', function () { return frisby.fetch('https://api.example.com/path%00.md', {}, { urlEncode: false }) .expect('status', 200); }); ``` -------------------------------- ### OPTIONS Request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP OPTIONS request to check allowed methods and CORS headers. ```APIDOC ## OPTIONS [URL] ### Description Makes an HTTP OPTIONS request to check allowed methods and CORS headers. ### Method OPTIONS ### Response #### Success Response (204) ``` -------------------------------- ### Define and Use Custom Expect Handler Source: https://github.com/vlucas/frisby/blob/master/README.md Shows how to define a reusable custom expectation handler using `frisby.addExpectHandler` and then use it in tests. Custom handlers can encapsulate complex assertions. Ensure Frisby is imported. ```javascript beforeAll(function () { // Add our custom expect handler frisby.addExpectHandler('isUser1', function (response) { let json = response.body; // Run custom Jasmine matchers here expect(json.id).toBe(1); expect(json.email).toBe('testy.mctesterpants@example.com'); }); }); // Use our new custom expect handler it('should allow custom expect handlers to be registered and used', function () { return frisby.get('https://api.example.com/users/1') .expect('isUser1') }); afterAll(function () { // Remove said custom handler (if needed) frisby.removeExpectHandler('isUser1'); }); ``` -------------------------------- ### Perform HEAD request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP HEAD request to check resource metadata without fetching the body. ```javascript const frisby = require('frisby'); it('should check Content-Length header', function () { return frisby.head('https://api.example.com/users') .expect('status', 200) .then(function(response) { let length = Number(response.headers.get('Content-Length')); expect(length).toBeLessThan(1000); }); }); ``` -------------------------------- ### Handle errors with catch() Source: https://context7.com/vlucas/frisby/llms.txt Manage promise chain errors to test failure scenarios or perform recovery requests. ```javascript const frisby = require('frisby'); it('should handle errors with catch()', function () { return frisby.setup({ request: { inspectOnFailure: false } }) .get('https://api.example.com/invalid') .expect('json', { id: 999 }) .catch(function (err) { expect(err.name).toContain('AssertionError'); // Return a recovery request return frisby.get('https://api.example.com/users/1') .expect('json', { id: 1 }); }); }); ``` -------------------------------- ### Chain operations with then() Source: https://context7.com/vlucas/frisby/llms.txt Access response data or initiate nested requests after the initial fetch completes. ```javascript const frisby = require('frisby'); it('should chain with then()', function () { return frisby.get('https://api.example.com/users/1') .expect('status', 200) .then(function (res) { expect(res.json.id).toBe(1); expect(res.json.email).toBe('joe.schmoe@example.com'); }); }); it('should return nested Frisby spec from then()', function () { return frisby.get('https://api.example.com/users/1') .expect('json', { id: 1 }) .then(function () { return frisby.get('https://api.example.com/users/2') .expect('json', { id: 2 }); }) .then(function (res) { // res is from the nested request expect(res.json.id).toBe(2); }); }); ``` -------------------------------- ### Handle Nested Test Chains Source: https://context7.com/vlucas/frisby/llms.txt Create deeply nested test chains for complex workflows using callbacks. Ensure the `doneFn` is called upon completion of the final asynchronous operation. ```javascript const frisby = require('frisby'); it('should handle nested test chains', function (doneFn) { frisby.get('https://api.example.com/users/1') .expect('status', 200) .then(function(response) { // Delete the user based on previous response frisby.del('https://api.example.com/users/' + response.json.id) .expect('status', 204) .done(doneFn); }); }); ``` -------------------------------- ### HEAD Request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP HEAD request to check resource metadata. ```APIDOC ## HEAD [URL] ### Description Makes an HTTP HEAD request to check resource metadata without fetching the body. ### Method HEAD ### Response #### Success Response (200) ``` -------------------------------- ### Execute cleanup with finally() Source: https://context7.com/vlucas/frisby/llms.txt Run cleanup logic regardless of whether the test succeeded or failed. ```javascript const frisby = require('frisby'); it('should execute finally()', function () { let cleanupRan = false; return frisby.get('https://api.example.com/users/1') .expect('status', 200) .finally(() => { cleanupRan = true; }) .then(() => { expect(cleanupRan).toBe(true); }); }); ``` -------------------------------- ### Perform POST request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP POST request with automatic JSON body serialization. ```javascript const frisby = require('frisby'); it('should create a new user', function () { return frisby.post('https://api.example.com/users', { body: { email: 'user@example.com', password: 'password' } }) .expect('status', 201) .expect('json', { id: 2, email: 'user@example.com' }); }); ``` -------------------------------- ### Perform PUT request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP PUT request for updating existing resources with automatic JSON serialization. ```javascript const frisby = require('frisby'); it('should update an existing user', function () { return frisby.put('https://api.example.com/users/1', { body: { email: 'updated@example.com', name: 'Updated Name' } }) .expect('status', 200) .expect('json', { id: 1, email: 'updated@example.com' }); }); ``` -------------------------------- ### Perform PATCH request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP PATCH request for partial resource updates. ```javascript const frisby = require('frisby'); it('should partially update a user', function () { return frisby.patch('https://api.example.com/users/1', { body: { name: 'New Name' } }) .expect('status', 200); }); ``` -------------------------------- ### POST Request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP POST request with automatic JSON body serialization. ```APIDOC ## POST [URL] ### Description Makes an HTTP POST request with automatic JSON body serialization. ### Method POST ### Request Body - **body** (object) - JSON object containing request data ### Request Example { "email": "user@example.com", "password": "password" } ### Response #### Success Response (201) - **id** (number) - Created resource ID - **email** (string) - Created resource email ``` -------------------------------- ### PUT Request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP PUT request for updating existing resources. ```APIDOC ## PUT [URL] ### Description Makes an HTTP PUT request for updating existing resources. ### Method PUT ### Request Body - **body** (object) - JSON object containing update data ### Request Example { "email": "updated@example.com", "name": "Updated Name" } ### Response #### Success Response (200) - **id** (number) - Resource ID - **email** (string) - Updated email ``` -------------------------------- ### Validate HTTP Status Codes Source: https://context7.com/vlucas/frisby/llms.txt Use `expect('status', code)` to verify the HTTP response status code. Ensure the expected status code is provided. ```javascript const frisby = require('frisby'); it('should validate status codes', function () { return frisby.get('https://api.example.com/users/1') .expect('status', 200); }); it('should handle 204 No Content', function () { return frisby.get('https://api.example.com/contents/none') .expect('status', 204); }); ``` -------------------------------- ### Match Any One Array Item Source: https://context7.com/vlucas/frisby/llms.txt Tests that at least one item in an array matches the expectation. The question mark (?) wildcard is used for this. ```javascript const frisby = require('frisby'); it('should find at least one matching item', function () { return frisby.get('https://api.example.com/users') .expect('json', 'data.?', { id: 1, email: 'joe.schmoe@example.example.com' }) // Match a single field in any item .expect('json', 'data.?.email', 'joe.schmoe@example.example.com'); }); ``` -------------------------------- ### Per-Test Configuration - timeout() Source: https://context7.com/vlucas/frisby/llms.txt Sets the request timeout in milliseconds for a specific test. ```APIDOC ## timeout() ### Description Sets request timeout in milliseconds for a specific test. ### Method `frisby.timeout(ms)` ### Parameters - **ms** (number) - Required - The timeout duration in milliseconds. ### Request Example ```javascript const frisby = require('frisby'); it('should timeout after 10ms', function () { return frisby.timeout(10) .fetch('https://api.example.com/slow-endpoint') .catch(function (err) { expect(err.name).toBe('FetchError'); }); }); ``` ``` -------------------------------- ### Validate Response Headers Source: https://context7.com/vlucas/frisby/llms.txt Use `expect('header', name, value)` to check if response headers exist and optionally match a specific value. Header names are case-insensitive. Supports exact string and regex matching. ```javascript const frisby = require('frisby'); it('should validate headers', function () { return frisby.get('https://api.example.com/users/1') // Check header exists .expect('header', 'Content-Type') // Exact match (case insensitive on header name) .expect('header', 'Content-Type', 'application/json') // Regex match .expect('header', 'Content-Type', /json/) // Check header does NOT have a value .expectNot('header', 'Content-Type', /xml/); }); ``` -------------------------------- ### expect('header', name, [value]) Source: https://context7.com/vlucas/frisby/llms.txt Validates response headers exist and optionally match a value. Supports exact string matching and regular expressions. Header names are case-insensitive. ```APIDOC ## expect('header', name, [value]) ### Description Validates response headers exist and optionally match a value. Supports exact string matching and regular expressions. Header names are case-insensitive. ### Method GET (example) ### Endpoint https://api.example.com/users/1 (example) ### Parameters #### Query Parameters - **name** (string) - Required - The name of the header to check. - **value** (string | RegExp) - Optional - The expected value of the header. ### Request Example ```javascript frisby.get('https://api.example.com/users/1') .expect('header', 'Content-Type') // Check header exists .expect('header', 'Content-Type', 'application/json') // Exact match .expect('header', 'Content-Type', /json/) // Regex match .expectNot('header', 'Content-Type', /xml/); // Check header does NOT have a value ``` ### Response #### Success Response (200) - **header** (string) - The value of the specified header. #### Response Example ```json { "Content-Type": "application/json" } ``` ``` -------------------------------- ### Signal completion with done() Source: https://context7.com/vlucas/frisby/llms.txt Use the done callback for Jasmine async tests instead of returning a promise. ```javascript const frisby = require('frisby'); it('should use done callback', function (doneFn) { frisby.get('https://api.example.com/users/1') .expect('status', 200) .done(doneFn); }); ``` -------------------------------- ### Register and use custom expect handlers Source: https://context7.com/vlucas/frisby/llms.txt Define reusable validation logic with addExpectHandler and remove them when finished. Handlers can accept additional arguments for dynamic validation. ```javascript const frisby = require('frisby'); beforeAll(function () { // Register custom expect handler frisby.addExpectHandler('isUser1', function (response) { let json = response.json; expect(json.id).toBe(1); expect(json.email).toBe('joe.schmoe@example.com'); }); // Handler with arguments frisby.addExpectHandler('hasUserWithId', function (response, expectedId) { expect(response.json.id).toBe(expectedId); }); }); it('should use custom expect handler', function () { return frisby.get('https://api.example.com/users/1') .expect('isUser1'); }); it('should use custom handler with arguments', function () { return frisby.get('https://api.example.com/users/1') .expect('hasUserWithId', 1); }); afterAll(function () { frisby.removeExpectHandler('isUser1'); frisby.removeExpectHandler('hasUserWithId'); }); ``` -------------------------------- ### Using Jasmine Matchers Directly in `then` Source: https://github.com/vlucas/frisby/blob/master/README.md Illustrates how to use standard Jasmine matchers within the `then` block of a Frisby request to perform custom assertions on the response data. Ensure Frisby is imported. ```javascript const frisby = require('frisby'); it('should be user 1', function () { return frisby.get('https://api.example.com/users/1') .then(function (res) { expect(res.json.id).toBe(1); expect(res.json.email).toBe('testy.mctesterpants@example.com'); }); }); ``` -------------------------------- ### Nested Dependent HTTP Calls with JSON Validation Source: https://github.com/vlucas/frisby/blob/master/README.md Demonstrates chaining HTTP requests where subsequent requests depend on the response of previous ones. Includes JSON structure and type validation using Joi. Ensure Frisby and Joi are imported. ```javascript const frisby = require('frisby'); const Joi = require('joi'); describe('Posts', function () { it('should return all posts and first post should have comments', function () { return frisby.get('http://jsonplaceholder.typicode.com/posts') .expect('status', 200) .expect('jsonTypes', '*', { userId: Joi.number(), id: Joi.number(), title: Joi.string(), body: Joi.string() }) .then(function (res) { // res = FrisbyResponse object let postId = res.json[0].id; // Get first post's comments // RETURN the FrisbySpec object so function waits on it to finish - just like a Promise chain return frisby.get('http://jsonplaceholder.typicode.com/posts/' + postId + '/comments') .expect('status', 200) .expect('json', '*', { postId: postId }) .expect('jsonTypes', '*', { postId: Joi.number(), id: Joi.number(), name: Joi.string(), email: Joi.string().email(), body: Joi.string() }); }); }); }); ``` -------------------------------- ### Set Global Base URL Source: https://context7.com/vlucas/frisby/llms.txt Sets a global base URL for all subsequent requests, allowing the use of relative paths in your tests. This simplifies test writing when targeting a single API. ```javascript const frisby = require('frisby'); // Set base URL globally frisby.baseUrl('https://api.example.com'); it('should use relative URL with base', function () { return frisby.fetch('/users/1') .expect('status', 200); }); ``` -------------------------------- ### expect('jsonTypesStrict', [path], schema) Source: https://context7.com/vlucas/frisby/llms.txt Validates JSON types with strict mode - extra keys not defined in the schema will cause failures. ```APIDOC ## expect('jsonTypesStrict', [path], schema) ### Description Validates JSON types with strict mode - extra keys not defined in the schema will cause failures. ### Method GET (example) ### Endpoint https://api.example.com/users/1 (example) ### Parameters #### Query Parameters - **path** (string) - Optional - The path to the JSON property to validate (e.g., 'user.name'). - **schema** (object) - Required - A Joi schema object defining the expected types and structure (strict mode). ### Request Example ```javascript const Joi = frisby.Joi; frisby.fromJSON({ name: 'john', foo: 'bar' }) .expect('jsonTypesStrict', { name: Joi.string(), foo: Joi.string() }); frisby.fromJSON({ name: 'john', foo: 'bar' }) .expectNot('jsonTypesStrict', { name: Joi.string() }); // This would fail because 'foo' is not in schema ``` ### Response #### Success Response (200) - **jsonTypesStrict** (object | array) - The JSON response body validated strictly against the Joi schema. #### Response Example ```json { "name": "john", "foo": "bar" } ``` ``` -------------------------------- ### expect('status', code) Source: https://context7.com/vlucas/frisby/llms.txt Validates the HTTP response status code matches the expected value. ```APIDOC ## expect('status', code) ### Description Validates the HTTP response status code matches the expected value. ### Method GET (example) ### Endpoint https://api.example.com/users/1 (example) ### Request Example ```javascript frisby.get('https://api.example.com/users/1').expect('status', 200); ``` ### Response #### Success Response (200) - **status** (number) - The HTTP status code of the response. #### Response Example ```json { "status": 200 } ``` ``` -------------------------------- ### Perform inline custom expectations Source: https://context7.com/vlucas/frisby/llms.txt Pass a function directly to expect() for one-off validations that do not require global registration. ```javascript const frisby = require('frisby'); it('should use inline custom function', function () { return frisby.get('https://api.example.com/users/1') .expect(function (response) { expect(response.json.id).toBeGreaterThan(0); expect(response.json.email).toContain('@'); }); }); ``` -------------------------------- ### Access internal promise with promise() Source: https://context7.com/vlucas/frisby/llms.txt Retrieve the underlying Promise for advanced scenarios, noting that this terminates chainability. ```javascript const frisby = require('frisby'); it('should access internal promise', async function () { const response = await frisby.get('https://api.example.com/users/1') .expect('status', 200) .promise(); expect(response.json.id).toBe(1); }); ``` -------------------------------- ### PATCH Request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP PATCH request for partial resource updates. ```APIDOC ## PATCH [URL] ### Description Makes an HTTP PATCH request for partial resource updates. ### Method PATCH ### Request Body - **body** (object) - JSON object containing partial update data ### Request Example { "name": "New Name" } ### Response #### Success Response (200) ``` -------------------------------- ### expect('jsonStrict', [path], value) Source: https://context7.com/vlucas/frisby/llms.txt Validates JSON response body matches exactly. Unlike 'json', extra keys or missing keys will cause test failures. ```APIDOC ## expect('jsonStrict', [path], value) ### Description Validates JSON response body matches exactly. Unlike 'json', extra keys or missing keys will cause test failures. ### Method GET (example) ### Endpoint https://api.example.com/users/1 (example) ### Parameters #### Query Parameters - **path** (string) - Optional - The path to the JSON property to validate (e.g., 'user.name'). - **value** (object | string | number | boolean | RegExp | array) - Required - The exact expected value or structure. ### Request Example ```javascript frisby.get('https://api.example.com/users/1') .expect('jsonStrict', { id: 1, email: 'joe.schmoe@example.com' }); frisby.get('https://api.example.com/users/1') .expectNot('jsonStrict', { email: 'joe.schmoe@example.com' }); // This would fail because it requires exact match ``` ### Response #### Success Response (200) - **jsonStrict** (object | array) - The JSON response body, matching exactly. #### Response Example ```json { "id": 1, "email": "joe.schmoe@example.com" } ``` ``` -------------------------------- ### expect('json', [path], value) Source: https://context7.com/vlucas/frisby/llms.txt Validates JSON response body contains the expected structure and values. Supports optional path for nested object access and RegExp matching for values. ```APIDOC ## expect('json', [path], value) ### Description Validates JSON response body contains the expected structure and values. Supports optional path for nested object access and RegExp matching for values. ### Method GET (example) ### Endpoint https://api.example.com/users/1 (example) ### Parameters #### Query Parameters - **path** (string) - Optional - The path to the JSON property to validate (e.g., 'user.name'). - **value** (object | string | number | boolean | RegExp | array) - Required - The expected value or structure. ### Request Example ```javascript frisby.get('https://api.example.com/users/1') .expect('json', { id: 1, email: 'joe.schmoe@example.com' }) .expect('json', 'id', 1) .expect('json', 'email', /joe\.\w+@\w+\.\w{3}/); frisby.fromJSON({ one: { two: { three: 3 } } }) .expect('json', 'one.two', { three: 3 }) .expect('json', 'one.two.three', 3); frisby.fromJSON(['a', 1, true, null]) .expect('json', ['a', 1, true, null]) .expect('json', ['a', 1]); // Partial array match ``` ### Response #### Success Response (200) - **json** (object | array) - The JSON response body. #### Response Example ```json { "id": 1, "email": "joe.schmoe@example.com" } ``` ``` -------------------------------- ### Match All Object Values Source: https://context7.com/vlucas/frisby/llms.txt Tests every value in an object (not an array) to ensure they match the expectation. The ampersand (&) wildcard is used for this, similar to the asterisk for arrays. ```javascript const frisby = require('frisby'); const Joi = frisby.Joi; it('should validate all object values', function () { // Response: { data: { joe: {...}, testy: {...} } } return frisby.get('https://api.example.com/users.name') .expect('jsonTypes', 'data.&', { id: Joi.number(), email: Joi.string().email() }) .expect('jsonTypes', 'data.&.id', Joi.number()); }); ``` -------------------------------- ### expect('jsonTypes', [path], schema) Source: https://context7.com/vlucas/frisby/llms.txt Validates JSON response structure and value types using Joi schema validation. Allows extra keys not defined in the schema by default. ```APIDOC ## expect('jsonTypes', [path], schema) ### Description Validates JSON response structure and value types using Joi schema validation. Allows extra keys not defined in the schema by default. ### Method GET (example) ### Endpoint https://api.example.com/users/1 (example) ### Parameters #### Query Parameters - **path** (string) - Optional - The path to the JSON property to validate (e.g., 'user.name'). - **schema** (object) - Required - A Joi schema object defining the expected types and structure. ### Request Example ```javascript const Joi = frisby.Joi; frisby.get('https://api.example.com/users/1') .expect('jsonTypes', { id: Joi.number(), email: Joi.string().email() }); frisby.fromJSON({ one: { foo: 'bar', two: { three: 3 } } }) .expect('jsonTypes', { one: { foo: Joi.string(), two: { three: Joi.number() } } }) .expect('jsonTypes', 'one.two.three', Joi.number()); // Or use path frisby.get('https://api.example.com/posts') .expect('jsonTypes', '*', { userId: Joi.number(), id: Joi.number(), title: Joi.string(), body: Joi.string() }); // Validate array of objects ``` ### Response #### Success Response (200) - **jsonTypes** (object | array) - The JSON response body validated against the Joi schema. #### Response Example ```json { "id": 1, "email": "joe.schmoe@example.com" } ``` ``` -------------------------------- ### Mock JSON Responses with fromJSON() Source: https://context7.com/vlucas/frisby/llms.txt Load JSON data directly without making an HTTP request using `frisby.fromJSON()`. This is useful for unit testing expectations against known data structures and validating JSON types. ```javascript const frisby = require('frisby'); const Joi = frisby.Joi; it('should test JSON without HTTP request', function () { return frisby.fromJSON({ foo: 'bar', nested: { value: 123 } }) .expect('json', { foo: 'bar' }) .expect('json', 'nested.value', 123) .expect('jsonTypes', { foo: Joi.string(), nested: { value: Joi.number() } }); }); ``` -------------------------------- ### JSON Path Selectors Source: https://context7.com/vlucas/frisby/llms.txt Provides methods for accessing and validating specific elements within JSON responses using various selectors. ```APIDOC ## JSON Path Selectors ### Array Index Access Access specific array elements using dot notation or bracket syntax for precise JSON validation. #### Example (Dot Notation) ```javascript frisby.get('https://api.example.com/users') .expect('json', 'data.0', { id: 1, email: 'joe.schmoe@example.com' }); ``` #### Example (Bracket Notation) ```javascript frisby.get('https://api.example.com/users') .expect('json', 'data[0]', { id: 1, email: 'joe.schmoe@example.com' }); ``` #### Example (Nested Path with Index) ```javascript frisby.get('https://api.example.com/users') .expect('json', 'data.0.id', 1); ``` ### Asterisk (*) - Match All Items Tests every item in an array or object. All items must pass the expectation. #### Example ```javascript const Joi = frisby.Joi; frisby.get('https://api.example.com/users') .expect('jsonTypes', 'data.*', { id: Joi.number(), email: Joi.string().email() }); ``` ### Question Mark (?) - Match Any One Item Tests that at least one item in an array or object matches the expectation. #### Example ```javascript frisby.get('https://api.example.com/users') .expect('json', 'data.?', { id: 1, email: 'joe.schmoe@example.com' }); ``` ### Ampersand (&) - Match All Object Values Tests every value in an object (not array). Similar to asterisk but specifically for objects. #### Example ```javascript const Joi = frisby.Joi; frisby.get('https://api.example.com/users.name') .expect('jsonTypes', 'data.&', { id: Joi.number(), email: Joi.string().email() }); ``` ``` -------------------------------- ### Use Negative Assertions with expectNot() Source: https://context7.com/vlucas/frisby/llms.txt Invert expectations to test that conditions do NOT match using `expectNot()`. This is useful for verifying that certain states or data are absent in the response. ```javascript const frisby = require('frisby'); it('should use negative assertions', function () { return frisby.get('https://api.example.com/users/1') .expectNot('status', 404) .expectNot('header', 'Content-Type', 'text/xml') .expectNot('json', { id: 999 }); }); ``` -------------------------------- ### Validate All Array Items Source: https://context7.com/vlucas/frisby/llms.txt Tests every item in an array to ensure they all pass the expectation. Use the asterisk (*) wildcard for this purpose. ```javascript const frisby = require('frisby'); const Joi = frisby.Joi; it('should validate every item in array', function () { return frisby.get('https://api.example.com/users') .expect('jsonTypes', 'data.*', { id: Joi.number(), email: Joi.string().email() }) // Validate single field across all items .expect('jsonTypes', 'data.*.id', Joi.number()); }); ``` -------------------------------- ### Pass Cookies Between Requests Source: https://context7.com/vlucas/frisby/llms.txt Handle cookies between requests for testing authenticated flows. This involves setting a cookie in one request and then including it in subsequent requests to maintain session state. ```javascript const frisby = require('frisby'); it('should pass cookies between requests', function () { return frisby.get('https://api.example.com/cookies/set') .expect('status', 200) .expect('header', 'Set-Cookie') .then((res) => { let cookie = res.headers.get('Set-Cookie'); return frisby.get('https://api.example.com/cookies/check', { headers: { 'Cookie': cookie } }) .expect('status', 200); }); }); ``` -------------------------------- ### Expect Response Time Source: https://context7.com/vlucas/frisby/llms.txt Validates that a request completed within a specified time limit in milliseconds. Ensure the maximum time is provided as an argument. ```javascript const frisby = require('frisby'); it('should respond within 500ms', function () { return frisby.get('https://api.example.com/users/1') .expect('status', 200) .expect('responseTime', 500); }); ``` -------------------------------- ### Upload File with FormData Source: https://context7.com/vlucas/frisby/llms.txt Upload files using FormData. Frisby automatically handles the `Content-Type` header for `multipart/form-data` requests. Ensure the file path is correct. ```javascript const frisby = require('frisby'); const fs = require('fs'); it('should upload a file', function () { let form = frisby.formData(); form.append('file', fs.createReadStream('/path/to/image.png')); return frisby.post('https://api.example.com/upload', { body: form }) .expect('status', 200) .expect('header', 'Content-Type', 'image/png'); }); ``` -------------------------------- ### Perform DELETE request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP DELETE request, optionally including a request body. ```javascript const frisby = require('frisby'); it('should delete users by ID', function () { return frisby.delete('https://api.example.com/users', { body: { data: [ { id: 2 }, { id: 3 } ] } }) .expect('status', 200) .expect('json', { data: [ { id: 2 }, { id: 3 } ] }); }); ``` -------------------------------- ### Chain Dependent HTTP Requests Source: https://context7.com/vlucas/frisby/llms.txt Execute sequential HTTP requests where each subsequent request uses data from the previous response. Ensure the first request is successful and its JSON response is correctly typed before proceeding. ```javascript const frisby = require('frisby'); const Joi = frisby.Joi; it('should chain dependent requests', function () { return frisby.get('https://jsonplaceholder.typicode.com/posts') .expect('status', 200) .expect('jsonTypes', '*', { userId: Joi.number(), id: Joi.number(), title: Joi.string(), body: Joi.string() }) .then(function (res) { let postId = res.json[0].id; // Get first post's comments using data from previous response return frisby.get('https://jsonplaceholder.typicode.com/posts/' + postId + '/comments') .expect('status', 200) .expect('json', '*', { postId: postId }) .expect('jsonTypes', '*', { postId: Joi.number(), id: Joi.number(), name: Joi.string(), email: Joi.string().email(), body: Joi.string() }); }); }); ``` -------------------------------- ### Response Time Expectation Source: https://context7.com/vlucas/frisby/llms.txt Validates that the request completed within the specified time limit in milliseconds. ```APIDOC ## expect('responseTime', maxMs) ### Description Validates that the request completed within the specified time limit in milliseconds. ### Method Implicitly GET (or other HTTP methods used by frisby) ### Endpoint N/A (Applies to any request) ### Request Example ```javascript const frisby = require('frisby'); it('should respond within 500ms', function () { return frisby.get('https://api.example.com/users/1') .expect('status', 200) .expect('responseTime', 500); }); ``` ### Response N/A (This is an assertion, not a response structure) ``` -------------------------------- ### Access Array Elements by Index Source: https://context7.com/vlucas/frisby/llms.txt Access specific array elements using dot notation or bracket syntax for precise JSON validation. This is useful for targeting individual items within a JSON response array. ```javascript const frisby = require('frisby'); const Joi = frisby.Joi; it('should access array elements by index', function () { return frisby.get('https://api.example.com/users') // Dot notation .expect('json', 'data.0', { id: 1, email: 'joe.schmoe@example.example.com' }) // Bracket notation .expect('json', 'data[0]', { id: 1, email: 'joe.schmoe@example.example.com' }) // Nested path with index .expect('json', 'data.0.id', 1); }); ``` -------------------------------- ### Debug Responses with Inspectors Source: https://context7.com/vlucas/frisby/llms.txt Debug responses by logging various parts of the request/response cycle using Frisby's inspector methods. These methods help in understanding the flow and content of HTTP requests and responses. ```javascript const frisby = require('frisby'); it('should inspect response data', function () { return frisby.get('https://api.example.com/users/1') .inspectRequest() // Log full request .inspectRequestHeaders() // Log request headers .inspectResponse() // Log full response .inspectHeaders() // Log response headers .inspectStatus() // Log status code .inspectBody() // Log body .inspectJSON() // Log parsed JSON .expect('status', 200); }); ``` -------------------------------- ### DELETE Request Source: https://context7.com/vlucas/frisby/llms.txt Makes an HTTP DELETE request, optionally including a request body. ```APIDOC ## DELETE [URL] ### Description Makes an HTTP DELETE request. ### Method DELETE ### Request Body - **body** (object) - Optional request body ### Request Example { "data": [{"id": 2}, {"id": 3}] } ### Response #### Success Response (200) ```