Using async await

If the asynchronous function that we are testing is using promises, then we can easily include the async await syntax to run asynchronous tests. As an example, let's build a class that uses a promise to return a value, as follows:

class MockAsyncWithPromiseClass { 
    delayedPromise(): Promise<string> { 
        return new Promise<string> 
            ((resolve: (str: string) => void, 
                reject: (str: string) => void 
            ) => { 
                function afterTimeout() { 
                    console.log(`2. resolving promise`); 
                    resolve('success'); 
                } 
                setTimeout(afterTimeout, 1000); 
            }); 
    } 
} 

Here, we have a class named MockAsyncWithPromiseClass that has a single function named delayedPromise, which returns a promise of type string. Within this function, we set up an anonymous function named afterTimeout, which will resolve the promise with the 'success' value. We then call this internal anonymous function after 1 second. As with our earlier asynchronous functions, this means that the promise will only be fulfilled after 1 second. Our unit test can now use the asyncawait keywords as follows:

describe("async test with async keyword", () => { 
    it("should wait for async to return with value ", async () => { 
        let mockAsyncWithPromise = new MockAsyncWithPromiseClass(); 
        let returnedValue!: string; 
        console.log(`1. calling delayedPromise`); 
        returnedValue = await mockAsyncWithPromise.delayedPromise(); 
        console.log(`3. checking returnedValue`); 
        expect(returnedValue).toEqual("success"); 
    }); 
}); 

Here, we have a test named "it should wait for async to return". Note how we have included the async keyword after the test description. This allows us to use the await keyword within this test function.

Our test starts by creating an instance of MockAsyncWithPromiseClass. We then call the delayedPromise function using the await keyword, and assign the result to the variable named returnedValue. Note that we have a couple of console logs to show the order of execution of the functions within this test. Running this test will show that using the await keyword with a function that returns a promise behaves as expected:

1. calling delayedPromise
2. resolving promise
3. checking returnedValue
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.42.94