javascriptnode.jsunit-testingtestingtap

Is there a way to define variables usable in all subtests in node tap?


I was wondering if there's a way to declare a variable before all the subtests in node tap js in order to use it in each one of them. Something like this:

      tap.test('...', async (t) => {
         
        t.before(async () => {
           const myVariable = ...
        }

        t.test('SubTest 1', async (t) => {
           await someMethod(myVariable)
        }

        t.test('SubTest 2', async (t) => {
           await someMethod(myVariable)
        }
      }  

It can be achieved another way, the idea is that I'd like to initialize some variables that I'll be using through all the subtests.


Solution

  • You need to move the variable declaration where the others can read it.

    tap.test('...', async (t) => {
      let myVariable;
      t.before(async () => {
        myVariable = '';
      }
    });