使用带角度的测试用fakeAsync进行角度测试

时间:2019-06-10 15:30:25

标签: angular jestjs angular-test angular-testing ts-jest

使用Angular 8,@ angular-builders / jest 8.0.2,jest 24.8,并通过以下测试通过

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();
}));

我想用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();
    }),
);

但是我在每次测试中都遇到了这个错误:

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

我想念什么?

2 个答案:

答案 0 :(得分:1)

到目前为止,我想到的最好的解决方法是将each部分移到describe包装器中,以便将fakeAsync用于“经典” 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();
        }));
    },
);

它给测试代码和控制台输出增加了一些干扰,但至少现在测试通过了。

答案 1 :(得分:0)

这似乎是jest-preset-angularzone-patch文件的问题。它不会修补it.eachtest.each使其在fakeAsync区域中运行。我已经提交了一个错误https://github.com/thymikee/jest-preset-angular/issues/339