{"id":16838,"library":"json-patch-test-suite","title":"JSON Patch Test Suite","description":"This package (`json-patch-test-suite`) serves as the official and community-maintained collection of test cases designed to validate implementations of the IETF JSON Patch specification (RFC 6902). It does not provide an actual JSON Patch implementation, but rather offers a standardized data set comprising source documents, applicable patches, and either the expected resulting document or a description of an anticipated error. The current stable version is 1.1.0. As a static test suite for a well-established RFC, its release cadence is infrequent, primarily occurring when new edge cases are identified or the RFC itself undergoes revisions. Its primary value lies in offering a neutral, comprehensive, and widely-adopted benchmark that allows developers to rigorously test their JSON Patch libraries for strict conformance to the RFC 6902 standard, ensuring interoperability and correctness across various programming languages and environments. This helps to prevent divergent interpretations of the specification.","status":"maintenance","version":"1.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/json-patch/json-patch-tests","tags":["javascript","JSON","Patch","test","suite"],"install":[{"cmd":"npm install json-patch-test-suite","lang":"bash","label":"npm"},{"cmd":"yarn add json-patch-test-suite","lang":"bash","label":"yarn"},{"cmd":"pnpm add json-patch-test-suite","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For ESM projects, import the `.json` file directly. Requires `\"resolveJsonModule\": true` in `tsconfig.json` (for TypeScript) or appropriate bundler configuration (e.g., Webpack, Rollup) to recognize JSON imports.","wrong":"import { tests } from 'json-patch-test-suite'","symbol":"tests","correct":"import tests from 'json-patch-test-suite/tests.json'"},{"note":"The `spec_tests.json` file contains test cases specifically derived from the RFC6902 specification document itself. It follows the same import patterns as `tests.json`.","wrong":"const specTests = require('json-patch-test-suite')","symbol":"specTests","correct":"import specTests from 'json-patch-test-suite/spec_tests.json'"},{"note":"For CommonJS projects, use `require()` with the full, explicit path to the `.json` file. Node.js correctly handles `require()` of JSON files by parsing them directly.","wrong":"const tests = require('json-patch-test-suite')","symbol":"tests","correct":"const tests = require('json-patch-test-suite/tests.json')"}],"quickstart":{"code":"import * as fs from 'fs';\nimport * as path from 'path';\n\n// IMPORTANT: This 'applyPatch' function is a placeholder.\n// You must integrate your actual JSON Patch implementation here\n// (e.g., from 'fast-json-patch', 'json-patch', etc.)\nconst applyPatch = (doc: any, patch: any[]): any => {\n  // In a real scenario, this would apply the patch and return the new document.\n  // For this example, we'll simulate a success or throw an error based on patch content.\n  if (!doc || !patch) throw new Error('Invalid input for patch application.');\n  if (patch.some((op: any) => op.path === '/invalid/path' && op.op === 'add')) {\n    throw new Error('Simulated patch error: Invalid path operation.');\n  }\n  return { ...doc, patched: true }; // Simulate a successful patch\n};\n\ninterface TestRecord {\n  doc: any;\n  patch: any[];\n  expected?: any;\n  error?: string;\n  comment?: string;\n  disabled?: boolean;\n}\n\n// Dynamically resolve the path to the installed json-patch-test-suite package.\n// This is generally safer than assuming 'node_modules' directly.\nconst resolvePackagePath = (packageName: string) => {\n  try {\n    return path.dirname(require.resolve(packageName + '/package.json'));\n  } catch (e) {\n    throw new Error(`Could not find package ${packageName}. Is it installed?`);\n  }\n};\n\nconst suitePackagePath = resolvePackagePath('json-patch-test-suite');\nconst testsPath = path.join(suitePackagePath, 'tests.json');\n\nconst testSuite: TestRecord[] = JSON.parse(fs.readFileSync(testsPath, 'utf8'));\n\nlet passedTests = 0;\nlet failedTests = 0;\n\nconsole.log(`Running ${testSuite.length} JSON Patch tests from the suite...\\n`);\n\ntestSuite.forEach((test, index) => {\n  if (test.disabled) {\n    // console.log(`Skipping disabled test [${index + 1}]: ${test.comment}`);\n    return;\n  }\n\n  try {\n    const result = applyPatch(test.doc, test.patch);\n\n    if (test.expected !== undefined) {\n      if (JSON.stringify(result) === JSON.stringify(test.expected)) {\n        passedTests++;\n      } else {\n        failedTests++;\n        console.error(`FAIL [${index + 1}]: ${test.comment || 'Unnamed test'}`);\n        console.error('  Doc:', JSON.stringify(test.doc));\n        console.error('  Patch:', JSON.stringify(test.patch));\n        console.error('  Expected:', JSON.stringify(test.expected));\n        console.error('  Got:', JSON.stringify(result));\n        console.error('--------------------------------------------------');\n      }\n    } else if (test.error !== undefined) {\n      failedTests++;\n      console.error(`FAIL [${index + 1}]: ${test.comment || 'Unnamed test'} (Expected error, but patch succeeded)`);\n      console.error('--------------------------------------------------');\n    }\n    // If no expected/error, assume success if no exception\n  } catch (e: any) {\n    if (test.error !== undefined) {\n      passedTests++; // We expected an error, and got one. Good enough for basic check.\n    } else {\n      failedTests++;\n      console.error(`FAIL [${index + 1}]: ${test.comment || 'Unnamed test'} (Unexpected error)`);\n      console.error('  Error:', e.message);\n      console.error('  Doc:', JSON.stringify(test.doc));\n      console.error('  Patch:', JSON.stringify(test.patch));\n      console.error('--------------------------------------------------');\n    }\n  }\n});\n\nconsole.log(`\\nTests finished: ${passedTests} passed, ${failedTests} failed.`);\nif (failedTests > 0) {\n  process.exit(1);\n}\n","lang":"typescript","description":"This quickstart demonstrates how to load the `tests.json` file from the `json-patch-test-suite` package and iterate through each test record. It shows how to integrate the test data with a hypothetical `applyPatch` function (which you would replace with your actual JSON Patch implementation) to validate its behavior against the suite's expected outcomes or errors. The example uses Node.js `fs` and `path` for file loading."},"warnings":[{"fix":"For TypeScript projects, ensure `\"resolveJsonModule\": true` and `\"esModuleInterop\": true` are set in your `tsconfig.json`'s `compilerOptions`. When using bundlers (e.g., Webpack, Rollup, Parcel), verify they are configured to handle JSON file imports (often built-in). For Node.js ESM, ensure your `package.json` specifies `\"type\": \"module\"` or use `.mjs` files for ESM modules.","message":"Direct JSON file imports require specific configuration in modern JavaScript environments.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"JSON Patch implementations may produce varying error messages. When `test.error` is present, focus on verifying that *an* error is thrown by your patching logic, rather than performing a strict string equality comparison against the `test.error` value. You might check for the *type* of error or a partial match for robustness.","message":"The `error` field in test records provides a *suggested* error message, not a definitive string for comparison.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Developers must integrate this test suite with their own JSON Patch library (e.g., `fast-json-patch`, `json-patch-js`) to actually apply the patches and validate the results. The quickstart example illustrates how to provide a placeholder `applyPatch` function that you would replace with your library's actual function.","message":"This package provides only JSON Patch test data, not an implementation of the RFC 6902 specification.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"For TypeScript, add `\"resolveJsonModule\": true` and `\"esModuleInterop\": true` to the `compilerOptions` in your `tsconfig.json`. If using a bundler (like Webpack), ensure your configuration includes a JSON loader (often enabled by default). Double-check the exact import path: `import tests from 'json-patch-test-suite/tests.json'`.","cause":"Your TypeScript configuration or JavaScript bundler is not set up to correctly resolve `.json` file imports, or the module resolution path is incorrect.","error":"Cannot find module 'json-patch-test-suite/tests.json'"},{"fix":"Ensure that your `require()` call explicitly targets the `.json` file extension (e.g., `const tests = require('json-patch-test-suite/tests.json')`). If using ESM in Node.js, confirm your `package.json` contains `\"type\": \"module\"` or use the `.mjs` extension for your module files, and configure your bundler/TypeScript to resolve JSON modules.","cause":"This typically occurs in older Node.js or CommonJS environments when `require()` or `import` attempts to parse a JSON file as a JavaScript module, or if the `require()` call does not specify the full `.json` extension.","error":"SyntaxError: Unexpected token '{' at <module-path>/node_modules/json-patch-test-suite/tests.json"}],"ecosystem":"npm","meta_description":null}