5

I want to write a simple test for my vue3 app, test should assert that specific function (updateRoute in this case) is declared with async in different components

Note: according to my current project I can't isolate this function in a single file to make it reusable

example:

const updateRoute = () => { doSomethig() }

should fail

while

const updateRoute = async () => { await doSomethig() }

should pass

the testing library doesn't matter, it can be Jest or anything else

ElsaKarami
  • 624
  • 1
  • 4
  • 14
B.Ch.
  • 220
  • 1
  • 10
  • 1
    It's not shown what is doSomethig and how updateRoute is used. It could be possibly solved with a linter. This can be XY problem. Even if it's known that updateRoute returns a promise, it's unknown that it returns a correct promise, i.e doSomethig is awaited. Generally it's preferable to assert that a place where updateRoute is used works correctly, i.e. side effects from doSomethig are applied at correct time. – Estus Flask Nov 18 '21 at 07:22

2 Answers2

2

There is no reliable way and no reason to detect async function. For a function that returns a promise, it's the same as:

const updateRoute = () => {
  return doSomethig().then(() => {}) // Returns a promise of undefined
}

It should be tested that updateRoute returns a promise, with async or not. In Jest it's:

expect(updateRoute()).toEqual(expect.any(Promise));

As for mandatory await, this can be handled with ESLint require-await rule if necessary.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
1

Check if the contructor.name of the function is equal to 'AsyncFunction':

const x = async () => {};
const y = () => {}

console.log(x.constructor.name);
console.log(x.constructor.name === 'AsyncFunction');

console.log(y.constructor.name);
console.log(y.constructor.name === 'AsyncFunction');
Gabriel Lupu
  • 1,397
  • 1
  • 13
  • 29