Asynchronous tests
As we have seen with our exploration of JavaScript and TypeScript, a lot of code we write is asynchronous. This means that we have no control of exactly when a callback will be invoked, or a Promise will resolve, as we are waiting for an event to occur that is outside of our control. This often presents problems in our unit testing, where we need to wait for an asynchronous event to complete before we can continue with our test. As an example of this, consider the following class:
class MockAsync {
executeSlowFunction(
complete: (value: string) => void
) {
setTimeout(() => {
complete(`completed`);
}, 1000);
}
}
Here, we have a class named MockAsync
that has a single method named executeSlowFunction
. This function takes a callback function named complete
as its only parameter, and then invokes it after 1 second. We might write a test for this class as follows:
describe("failing async tests"...