Home > front end >  How to test if function is called with async keyword
How to test if function is called with async keyword

Time:11-18

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

CodePudding user response:

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.

CodePudding user response:

you could test the following

Object.getPrototypeOf(updateRoute).constructor === Object.getPrototypeOf(async function(){}).constructor

Here's a demo

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


// demo
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
function test(fn) {
  return Object.getPrototypeOf(fn).constructor === AsyncFunction;
}
console.log(test(updateRoute)); // should be false
console.log(test(asyncUpdateRoute)); // should be true
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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');
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related