What is the difference between tick() and flush() in angular testing?
They do different things relative to async operations that were previously started. For example; calling setTimeout(...)
starts an async operation.
tick()
moves time forward.flush()
moves time to the end.
This can be better illustrated with the unit tests for those functions.
Tick
This unit test shows tick being used to move time forward in steps until all 10 timers have finished. Tick is called multiple times.
https://github.com/angular/angular/blob/master/packages/core/test/fake_async_spec.ts#L205
it('should clear periodic timers', fakeAsync(() => { let cycles = 0; const id = setInterval(() => { cycles++; }, 10); tick(10); expect(cycles).toEqual(1); discardPeriodicTasks(); // Tick once to clear out the timer which already started. tick(10); expect(cycles).toEqual(2); tick(10); // Nothing should change expect(cycles).toEqual(2); }));
Flush
This unit test shows that all async tasks should be finished when it returns, and that the returned value tells you how long it took for them to finish.
https://github.com/angular/angular/blob/master/packages/core/test/fake_async_spec.ts#L273
it('should flush multiple tasks', fakeAsync(() => { let ran = false; let ran2 = false; setTimeout(() => { ran = true; }, 10); setTimeout(() => { ran2 = true; }, 30); let elapsed = flush(); expect(ran).toEqual(true); expect(ran2).toEqual(true); expect(elapsed).toEqual(30); }));