apiaryio / dredd

Language-agnostic HTTP API Testing Tool
https://dredd.org
MIT License
4.18k stars 279 forks source link

Running dredd using async await #964

Open DavidFaizulaev opened 6 years ago

DavidFaizulaev commented 6 years ago

I'm writing a hooks.js file and would like to use the new option in node8 - async await. This requires me to pass only a single argument to BeforeEach, BeforeAll & AfterAll functions. This means that dredd will take as sync functions, which causes the tests to fail.

Is there a way to run dredd with async await?

Dredd version

dredd v5.0.0

This is the output I'm getting

warn: DEPRECATION WARNING!

You are using only one argument for the `beforeAll` or `afterAll` hook function.
One argument hook functions will be treated as synchronous in the near future.
To keep the async behaviour, just define hook function with two parameters.

Interface of the hooks functions will be unified soon across all hook functions:

 - `beforeAll` and `afterAll` hooks will support sync API depending on number of arguments
 - Signatures of callbacks of all hooks will be the same
 - First passed argument will be a `transactions` object
 - Second passed argument will be a optional callback function for async
 - `transactions` object in `hooks` module object will be removed
 - Manipulation with transaction data will have to be performed on the first function argument
hook: setting prime query
hook: setting prime query
honzajavorek commented 6 years ago

Yup, we should revamp how the JS hooks work. I would like them to work similar to tests in Mocha - if you pass callback, it's called, otherwise a promise is returned.

kylef commented 6 years ago

Something like the following would be a start at supporting the current behaviour alongside returning promises (or using async function as the hook):

diff --git a/src/transaction-runner.js b/src/transaction-runner.js
index cbdf1cc..b391165 100644
--- a/src/transaction-runner.js
+++ b/src/transaction-runner.js
@@ -315,12 +315,18 @@ Interface of the hooks functions will be unified soon across all hook functions:
     }
   }

-  runHook(hook, data, callback) {
+  async runHook(hook, data, callback) {
     // Not sandboxed mode - hook is a function
     if (typeof hook === 'function') {
       if (hook.length === 1) {
         // Sync api
-        hook(data);
+        const promise = hook(data);
+
+        if (promise) {
+          // Promise or async/await API
+          await promise;
+        }
+
         callback();
       } else if (hook.length === 2) {
         // Async api

This doesn't handle errors (rejected promises) properly to cause a failing test, but sharing as a start if anyone is tacking this issue.

okv commented 4 years ago

Hello there. Is somebody working on promises support for hooks? Could you provide some tips to start working on it.