using angular testing fakeAsync with jest it.each

Viewed 4603

Using Angular 8, @angular-builders/jest 8.0.2, jest 24.8, and given the following test passes

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

it('test 1000 milliseconds', fakeAsync(() => {
    const fn = jest.fn();
    setTimeout(() => {
        fn();
    }, 1000);

    tick(999);
    expect(fn).not.toHaveBeenCalled();
    tick(1);
    expect(fn).toHaveBeenCalled();
}));

I wanted to write several similar tests using it.each

it.each([[1000], [2000], [3000]])(
    'test %d milliseconds',
    fakeAsync(milliseconds => {
        const fn = jest.fn();
        setTimeout(() => {
            fn();
        }, milliseconds);

        tick(milliseconds - 1);
        expect(fn).not.toHaveBeenCalled();
        tick(1);
        expect(fn).toHaveBeenCalled();
    }),
);

but I got this error on each test:

Expected to be running in 'ProxyZone', but it was not found.

    at Function.Object.<anonymous>.ProxyZoneSpec.assertPresent (node_modules/zone.js/dist/proxy.js:42:19)
    at node_modules/zone.js/dist/fake-async-test.js:588:47

What am I missing ?

2 Answers

So far, the best workaround I thought of was to move the each part to a describe wrapper so that fakeAsync is used in a "classic" it.

describe.each([[1000], [2000], [3000]])(
    'test %d milliseconds',
    milliseconds => {
        it('', fakeAsync(() => {
            const fn = jest.fn();
            setTimeout(() => {
                fn();
            }, milliseconds);

            tick(milliseconds - 1);
            expect(fn).not.toHaveBeenCalled();
            tick(1);
            expect(fn).toHaveBeenCalled();
        }));
    },
);

It adds some noise to the test code and to the console output, but at least, the tests now pass.

Related