Skip to content

Commit

Permalink
feat: allow async/await syntax in code snippets
Browse files Browse the repository at this point in the history
pretty useful to be able to run asynchronous functions and collect data to pass to a request
  • Loading branch information
nima-taheri-hs committed Feb 20, 2023
1 parent d4db4da commit c47bca7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/plugins/javascript/moduleUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,14 @@ export async function runScript(
);

const contextKeys = Object.keys(context);
const compiledWrapper = vm.runInContext(Module.wrap(`${io.fileProvider.EOL}${source}`), context, {
const sourceAsync = `return (async()=>{${io.fileProvider.EOL}${source}})()`;
const compiledWrapper = vm.runInContext(Module.wrap(sourceAsync), context, {
filename,
lineOffset: options.lineOffset,
displayErrors: true,
breakOnSigint: true,
});
compiledWrapper.apply(context, [mod.exports, extendedRequire, mod, filename, path.dirname(filename)]);
await compiledWrapper.apply(context, [mod.exports, extendedRequire, mod, filename, path.dirname(filename)]);

deleteVariables(contextKeys, context, options.deleteVariable);

Expand Down
15 changes: 15 additions & 0 deletions src/test/variables/variables.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,19 @@ GET http://localhost:6005/test?test={{JSON.stringify(testObj)}}
const requests = await mockedEndpoints.getSeenRequests();
expect(requests[0].url).toBe('http://localhost:6005/test?test={%22bar%22:%22works%22}');
});

it('support await syntax in custom scripts', async () => {
initFileProvider();
const mockedEndpoints = await localServer.forGet('/test').thenJson(200, { slideshow: { author: 'httpyac' } });
await sendHttp(`
{{
const asyncFn = async () => ({ bar: 'works'});
exports.testObj = await asyncFn();
}}
GET http://localhost:6005/test?test={{JSON.stringify(testObj)}}
`);

const requests = await mockedEndpoints.getSeenRequests();
expect(requests[0].url).toBe('http://localhost:6005/test?test={%22bar%22:%22works%22}');
});
});

0 comments on commit c47bca7

Please sign in to comment.