diff --git a/src/__tests__/__snapshots__/plugins.spec.js.snap b/src/__tests__/__snapshots__/plugins.spec.js.snap index c2ece27..b5a29ac 100644 --- a/src/__tests__/__snapshots__/plugins.spec.js.snap +++ b/src/__tests__/__snapshots__/plugins.spec.js.snap @@ -1,24 +1,5 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`Beau's plugin system Dynamic Values should look for dynamic values executing and replacing them 1`] = ` -Object { - "body": "Hello World", - "request": Object { - "body": undefined, - "endpoint": "http://example.com/hello/3", - "headers": Object { - "count": "3", - "preRequestModifier": true, - }, - }, - "response": Object { - "body": "Hello World", - "headers": Array [], - "status": 200, - }, -} -`; - exports[`Beau's plugin system Request Modifiers should modify the request and response using modifiers. 1`] = ` Object { "body": "Hello World", diff --git a/src/__tests__/plugins.spec.js b/src/__tests__/plugins.spec.js index 60b2929..a0a86fa 100644 --- a/src/__tests__/plugins.spec.js +++ b/src/__tests__/plugins.spec.js @@ -65,21 +65,32 @@ describe(`Beau's plugin system`, () => { endpoint: 'http://example.com', alias: 'say-hello', headers: { - count: '$[add(1, $value2)]' - } + count: '$[add(1, $value2)]', + empty: '' + }, + payload: 'counted $[add(1, $value2)] so far.' }, plugins ); }); - it(`should look for dynamic values executing and replacing them`, async () => { - let cache = new RequestCache(); - cache.add('value2', '2'); + let cache = new RequestCache(); + cache.add('value2', '2'); + it(`should look for dynamic values executing and replacing them`, async () => { let req = await request.exec(cache); - expect(req).toHaveProperty('request.headers.count', '3'); - expect(req).toMatchSnapshot(); + expect(req).toHaveProperty('request.body', 'counted 3 so far.'); + }); + + it(`should change the internal datatype if the only thing in the value is the dynamic value`, async () => { + let req = await request.exec(cache); + expect(req).toHaveProperty('request.headers.count', 3); + }); + + it(`should return empty values as empty`, async () => { + let req = await request.exec(cache); + expect(req).toHaveProperty('request.headers.empty', ''); }); it(`should throw when calling an undefined dynamic value`, async () => { diff --git a/src/plugins.js b/src/plugins.js index c87e904..f0b15f7 100644 --- a/src/plugins.js +++ b/src/plugins.js @@ -47,7 +47,25 @@ class Plugins { replaceDynamicValues(obj) { return replaceInObject(obj, val => { + let valIsEmpty = val.trim().length === 0; + + if (valIsEmpty) { + return val; + } + try { + let onlyHasDynamic = + val.replace(dynamicValueRegex, '').trim() === ''; + + if (onlyHasDynamic) { + let call; + val.replace(dynamicValueRegex, (match, c) => { + call = c; + }); + + return vm.runInContext(call, this.context); + } + return val.replace(dynamicValueRegex, (match, call) => { return vm.runInContext(call, this.context); });