Sample codes

In the following code, we will cover the DoneFn interface, flush and tick methods to manage async operations and events.

import { fakeAsync, flush, tick } from "@angular/core/testing";

fdescribe('Async testing examples', () => {
    it('Async test example with Jasmine done', (done: DoneFn) => {
        let test = false;
        setTimeout(() => {
            test = true;
            expect(test).toBeTruthy();
            done();
        }, 1000);
    });

    it('Async test example - setTimeout()', fakeAsync(() => {
        let test = false;
        console.log('Running the assertions');
        setTimeout(() => {
            test = true;
            console.log('Running the assertions inside setTimeout()');
            expect(test).toBeTruthy();
        }, 1000);

        tick(1000);
    }));

    it('Async test example - setTimeout() with flush()', fakeAsync(() => {
        let test = false;
        
        setTimeout(() => {});

        setTimeout(() => {
            test = true;
            expect(test).toBeTruthy();
        }, 1000);

        flush();
    }));
});

Last updated