17. it(‘should have a value’, fakeAsync(() => {
element.querySelector(‘button’).click();
tick(1000);
fixture.detectChanges();
expect(element.textContent).toContain('0');
}));
So close…
Error: 1 periodic timer(s) still in the queue.
18. Description
If there are any pending timers at the end of the function, an
exception will be thrown.
Remain calm
19. it(‘should have a value’, fakeAsync(() => {
component.getNumbers();
tick(1000);
fixture.detectChanges();
expect(element.textContent).toContain(‘0');
}));
discardPeriodicTasks();
20. Chrome 66.0.3359 (Mac OS X 10.12.6): Executed 1 of 1 SUCCESS (0.135 secs / 0.127 secs)
21. ▸ flushMicrotasks()
‣ execute all remaining micro tasks
▸ flush()
▸ execute all remaining tasks
▸ fixture.whenStable()
▸ flush(), but different
What if I’m not testing an interval?
22. it('should set the flag', () => {
let flag = false;
Promise.resolve()
.then(() => flag = true);
expect(flag).toBe(true);
});
flushMicrotasks()
Expected false to be true.
23. it('should set the flag', (done) => {
let flag = false;
Promise.resolve()
.then(() => flag = true)
.then(() => {
expect(flag).toBe(true);
done();
});
});
The old-fashioned way
24. it('should set the flag', fakeAsync(() => {
let flag = false;
Promise.resolve()
.then(() => flag = true);
expect(flag).toBe(true);
}));
The Angular way
flushMicrotasks();
25. it('should set the flag', fakeAsync(() => {
const time = Math.random() * 10000;
let flag = false;
setTimeout(() => flag = true, time);
expect(flag).toBe(false);
const timeElapsed = flush();
expect(flag).toBe(true);
expect(timeElapsed).toBe(time);
}));
flush()
26. fixture.whenStable(): a different way to flush
it('should be true', fakeAsync(() => {
fixture.whenStable()
.then(() => expect(app.result).toBe(true));
}));
ngOnInit() {
someAsyncThing().then(() => this.result = true);
}
27. it('should be true', fakeAsync(() => {
fixture.whenRenderingDone()
.then(() => {
expect(app.result).toBe(true);
});
}));
And one last thing…
28. ▸ fixture.detectChanges()
▸ fakeAsync() zone
▸ tick(), flush() & flushMicrotasks()
▸ fixture.whenStable() & fixture.whenRenderingDone()
Our weapons in the fight against async tests