Repository: pactumjs/pactum
Pull request #322 (2024-03-18 13:13:19)

feat: find file in withJson


Patch:
diff --git a/package-lock.json b/package-lock.json
index d92c074..15ed8b4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
 {
   "name": "pactum",
-  "version": "3.6.2",
+  "version": "3.6.3",
   "lockfileVersion": 2,
   "requires": true,
   "packages": {
     "": {
       "name": "pactum",
-      "version": "3.6.2",
+      "version": "3.6.3",
       "license": "MIT",
       "dependencies": {
         "@exodus/schemasafe": "^1.3.0",
diff --git a/package.json b/package.json
index 2dfb80e..a4cf4c5 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
 {
   "name": "pactum",
-  "version": "3.6.2",
+  "version": "3.6.3",
   "description": "REST API Testing Tool for all levels in a Test Pyramid",
   "main": "./src/index.js",
   "types": "./src/index.d.ts",
diff --git a/src/config.js b/src/config.js
index d5172d7..404ef55 100644
--- a/src/config.js
+++ b/src/config.js
@@ -47,7 +47,8 @@ const config = {
       enabled: false,
       processed: false,
       direct_override: false,
-    }
+    },
+    dir: 'data'
   },
   strategy: {
     assert: {
diff --git a/src/exports/settings.d.ts b/src/exports/settings.d.ts
index c7da37c..04e8b7e 100644
--- a/src/exports/settings.d.ts
+++ b/src/exports/settings.d.ts
@@ -54,4 +54,5 @@ export function setCaptureHandlerStrategy(strategy: Strategy): void;
 export function setSnapshotDirectoryPath(path: string): void;
 export function setReporterAutoRun(auto: boolean): void;
 export function setRequestDefaultRetryCount(count: number): void;
-export function setRequestDefaultRetryDelay(delay: number): void;
\ No newline at end of file
+export function setRequestDefaultRetryDelay(delay: number): void;
+export function setDataDirectory(path: string): void;
\ No newline at end of file
diff --git a/src/exports/settings.js b/src/exports/settings.js
index b28a113..1c0e24e 100644
--- a/src/exports/settings.js
+++ b/src/exports/settings.js
@@ -57,6 +57,10 @@ const settings = {
 
   setRequestDefaultRetryDelay(delay) {
     config.request.retry.delay = delay;
+  },
+
+  setDataDirectory(path) {
+    config.data.dir = path;
   }
 
 };
diff --git a/src/helpers/file.utils.js b/src/helpers/file.utils.js
index 6dcbd09..588db26 100644
--- a/src/helpers/file.utils.js
+++ b/src/helpers/file.utils.js
@@ -1,4 +1,5 @@
 const fs = require('fs');
+const path = require('path');
 const config = require('../config');
 
 function getSnapshotDirAndName(name) {
@@ -27,7 +28,36 @@ function saveSnapshot(name, data) {
   fs.writeFileSync(`${snapshotDir}/${snapshotFile}`, JSON.stringify(data, null, 2));
 }
 
+/**
+ * 
+ * @param {string} name 
+ */
+function findFile(name, dir = config.data.dir) {
+  if (fs.existsSync(name)) {
+    return fs.readFileSync(name);
+  }
+  if (fs.existsSync(dir)) {
+    const exist = fs.existsSync(`${dir}/${name}`);
+    if (exist) {
+      return fs.readFileSync(`${dir}/${name}`);
+    }
+    // get folders in dir
+    const files = fs.readdirSync(dir);
+    for (const file of files) {
+      const dirPath = path.resolve(dir, file);
+      const stats = fs.statSync(dirPath);
+      if (stats.isDirectory()) {
+        const result = findFile(name, dirPath);
+        if (result) {
+          return result;
+        }
+      }
+    }
+  }
+}
+
 module.exports = {
   getSnapshotFile,
-  saveSnapshot
+  saveSnapshot,
+  findFile
 };
\ No newline at end of file
diff --git a/src/models/Spec.js b/src/models/Spec.js
index 364a24e..e11bcb4 100644
--- a/src/models/Spec.js
+++ b/src/models/Spec.js
@@ -14,6 +14,7 @@ const responseExpect = require('../exports/expect');
 const hr = require('../helpers/handler.runner');
 const rlc = require('../helpers/reporter.lifeCycle');
 const config = require('../config');
+const { findFile } = require('../helpers/file.utils');
 
 class Spec {
   constructor(name, data) {
@@ -192,7 +193,7 @@ class Spec {
 
   withJson(json) {
     if (typeof json === 'string') {
-      json = JSON.parse(fs.readFileSync(json));
+      json = JSON.parse(findFile(json));
     } else if (typeof json !== 'object') {
       throw new PactumRequestError(`Invalid json in request - ${json}`);
     }


Test patch:
diff --git a/test/component/withJson.spec.js b/test/component/withJson.spec.js
new file mode 100644
index 0000000..b3a7577
--- /dev/null
+++ b/test/component/withJson.spec.js
@@ -0,0 +1,51 @@
+const { spec, settings } = require('../../src/index');
+
+describe('withJson', () => {
+
+  before(() => {
+    settings.setDataDirectory('test/data');
+  });
+
+  after(() => {
+    settings.setDataDirectory('data');
+  });
+
+  it('with file in parent folder', async () => {
+    await spec()
+      .useInteraction({
+        request: {
+          method: 'POST',
+          path: '/file',
+          body: {
+            "key": "value-1"
+          }
+        },
+        response: {
+          status: 200
+        }
+      })
+      .post('http://localhost:9393/file')
+      .withJson('sample-1.json')
+      .expectStatus(200);
+  });
+
+  it('with file in child folder', async () => {
+    await spec()
+      .useInteraction({
+        request: {
+          method: 'POST',
+          path: '/file',
+          body: {
+            "key": "value-2"
+          }
+        },
+        response: {
+          status: 200
+        }
+      })
+      .post('http://localhost:9393/file')
+      .withJson('sample-2.json')
+      .expectStatus(200);
+  });
+  
+});
\ No newline at end of file
diff --git a/test/data/request/child/sample-2.json b/test/data/request/child/sample-2.json
new file mode 100644
index 0000000..4e2b0e0
--- /dev/null
+++ b/test/data/request/child/sample-2.json
@@ -0,0 +1,3 @@
+{
+  "key": "value-2"
+}
\ No newline at end of file
diff --git a/test/data/request/sample-1.json b/test/data/request/sample-1.json
new file mode 100644
index 0000000..6abbb35
--- /dev/null
+++ b/test/data/request/sample-1.json
@@ -0,0 +1,3 @@
+{
+  "key": "value-1"
+}
\ No newline at end of file