W3cubDocs

/Angular 12

tick

function

Simulates the asynchronous passage of time for the timers in the fakeAsync zone.

See more...

tick(millis: number = 0, tickOptions: { processNewMacroTasksSynchronously: boolean; } = { processNewMacroTasksSynchronously: true }): void

Parameters
millis number

The number of milliseconds to advance the virtual timer.

Optional. Default is 0.

tickOptions object

The options to pass to the tick() function.

Optional. Default is { processNewMacroTasksSynchronously: true }.

Returns

void

Description

The microtasks queue is drained at the very start of this function and after any timer callback has been executed.

Further information is available in the Usage Notes...

Usage notes

The tick() option is a flag called processNewMacroTasksSynchronously, which determines whether or not to invoke new macroTasks.

If you provide a tickOptions object, but do not specify a processNewMacroTasksSynchronously property (tick(100, {})), then processNewMacroTasksSynchronously defaults to true.

If you omit the tickOptions parameter (tick(100))), then tickOptions defaults to {processNewMacroTasksSynchronously: true}.

Example

describe('this test', () => {
  it('looks async but is synchronous', <any>fakeAsync((): void => {
       let flag = false;
       setTimeout(() => {
         flag = true;
       }, 100);
       expect(flag).toBe(false);
       tick(50);
       expect(flag).toBe(false);
       tick(50);
       expect(flag).toBe(true);
     }));
});

The following example includes a nested timeout (new macroTask), and the tickOptions parameter is allowed to default. In this case, processNewMacroTasksSynchronously defaults to true, and the nested function is executed on each tick.

it ('test with nested setTimeout', fakeAsync(() => {
  let nestedTimeoutInvoked = false;
  function funcWithNestedTimeout() {
    setTimeout(() => {
      nestedTimeoutInvoked = true;
    });
  };
  setTimeout(funcWithNestedTimeout);
  tick();
  expect(nestedTimeoutInvoked).toBe(true);
}));

In the following case, processNewMacroTasksSynchronously is explicitly set to false, so the nested timeout function is not invoked.

it ('test with nested setTimeout', fakeAsync(() => {
  let nestedTimeoutInvoked = false;
  function funcWithNestedTimeout() {
    setTimeout(() => {
      nestedTimeoutInvoked = true;
    });
  };
  setTimeout(funcWithNestedTimeout);
  tick(0, {processNewMacroTasksSynchronously: false});
  expect(nestedTimeoutInvoked).toBe(false);
}));

© 2010–2021 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v12.angular.io/api/core/testing/tick