angular - 角度测试: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.
我无法摆脱,因为fakeAsync
在beforeEach
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
});
});
解决方案
推荐阅读
- ios - 如果语句不适用于计时器
- firebase - AngularFire httpsCallable Object(...) 不是函数
- php - 查找带有图像 URL 的 XML 属性并下载它
- javascript - LazyLaoding CSS 背景(不是 HTML标签)
- javascript - 尝试更改 jquery 上一个和下一个按钮
- excel - 如何使用 VBA 从 Outlook 发送带有内联图像的电子邮件?
- java - Java Maze Solver - 调用 pop() 时堆栈不会弹出
- python - 我可以比较 unittest 中的 2 个浮点数的相似性但不相等吗?
- pattern-matching - Akka actor 中的接收方法
- c - C - 我的 scanf 永远不会停止接受输入