首页 > 解决方案 > 角度测试:tick 无法从其自己的 fakeAsync 区域之外的计时器中提前时间

问题描述

到目前为止,我发现的所有示例tick() 都与相同的计时器有关fakeAsync

考虑您有某种涉及的初始化,setTimeout并且您想将其放入beforeEach()并提前it(). 我不能只使用角度来做到这一点:(

请看下面的例子。为简单起见,“初始化”由一个简单的setTiemout. 任何关于tick不当行为的建议或更深入的解释,如果有办法克服它,将不胜感激。

这个总是失败,根本无法推进时间:

describe("counter1", () => {
        let counter = 0;
        beforeEach(() => {
            setTimeout(()=> ++counter, 10);
        });
        it("is incremented", fakeAsync(() => {
            expect(counter).toBe(0); // TRUE
            tick(50);
            expect(counter).toBe(1);  // FALSE; tick() can not advance the timer when it is outside the current fakeAsync
        }));
    });

这与上面的类似,但另外,Error: 1 timer(s) still in the queue.我无法摆脱,因为fakeAsyncbeforeEach

    describe("counter1fakeAsync" , () => {
        let counter = 0;
        beforeEach(fakeAsync(() => {
            setTimeout(()=> ++counter, 10);
        }));
        it("is incremented", fakeAsync(() => {
            expect(counter).toBe(0); // TRUE
            tick(50);
            expect(counter).toBe(1);  // FALSE; tick() can not advance the timer when it is outside the current fakeAsync
            // Even more you cannot get rid of `Error: 1 timer(s) still in the queue.`
        }));
    });

这行得通,Internet 上的所有示例都是这样的:

    describe("counter2",  () => {
        let counter = 0;
        it("is incremented", fakeAsync(() => {
            setTimeout(()=> ++counter, 10);
            expect(counter).toBe(0); // TRUE
            tick(50);
            expect(counter).toBe(1);  // TRUE; tick() can advance the timer if it is in the same fakeAsync
        }));
    });

jasmine.clock() 也可以:

    describe("counter3",  () => {
        let counter = 0;
        beforeEach(() => {
            jasmine.clock().uninstall(); // NEEDED :( or try with __zone_symbol__fakeAsyncPatchLock
            jasmine.clock().install();
            setTimeout(()=> ++counter, 10);
        });
        afterEach(() => {
            jasmine.clock().uninstall();
        });
        it("is incremented", () => {
            expect(counter).toBe(0); // TRUE
            jasmine.clock().tick(50);
            expect(counter).toBe(1);  // TRUE; jasmine.clock().tick() just works as expected
        });
    });

标签: angulartesting

解决方案


推荐阅读