Skip to content

Frames and element boxes ​

Two stubs for code that measures elements or waits for the next frame. jsdom and happy-dom lay nothing out, so every element measures 0 × 0, and they run frames on their own timers.

  • stubAnimationFrame() runs requestAnimationFrame callbacks when your spec says so.
  • stubElementRect() makes one element's getBoundingClientRect() return the box you give.
ts
import { expect, it } from 'vitest';
import { stubAnimationFrame, stubElementRect } from 'vitest-auto-spy/dom-stubs';

it('scrolls the selected row into view after the next frame', () => {
  const frames = stubAnimationFrame({ mode: 'queued' });

  stubElementRect(viewport, { height: 300 });
  list.select(42);

  expect(frames.pending).toBe(1);

  frames.flush();

  expect(list.firstVisibleRow()).toBe(42);
});

A zoneless Angular spec fails at the end of the file, and trackStrayTimers reports a stray requestAnimationFrame? Go to A stray frame reported from an Angular spec.

With setupAutoSpy() in your setup file, both stubs are removed after each test. A hand-written window.requestAnimationFrame = … is not removed. Neither is a partial object returned from getBoundingClientRect. Under isolate: false, the Vitest option that lets spec files share one environment, they leak into the next file.

stubAnimationFrame(options?) ​

Replaces requestAnimationFrame and cancelAnimationFrame with spies whose timing your spec decides.

OptionTypeDefaultMeaning
mode'immediate' | 'queued''immediate'When a requested frame runs; see below
onError(error) => void—Called with what a callback threw, instead of throwing it
viewobject | nulldocument.defaultViewAlso patch this window object; null patches globalThis only
modeA requested frame runs
'immediate'before requestAnimationFrame returns, with performance.now()
'queued'on flush(timestamp?), with the same timestamp for every frame

The returned handle:

MemberWhat it is
pendingHow many requested frames have not run
flush(timestamp?)Runs every frame requested so far, as one browser frame; timestamp defaults to performance.now()
flushAll(timestamp?)Runs frames until none is pending, including frames requested from inside a frame
lastHandleThe handle the latest requestAnimationFrame call returned; undefined before the first
requestAnimationFrame, cancelAnimationFrameThe installed spies, typed Mock<RequestAnimationFrameFn> / Mock<CancelAnimationFrameFn>
restore()Puts the previous globals back and drops what is pending, before the test ends

Rules worth knowing:

  • A frame requested inside a running frame waits for the next flush(), in both modes, as in a browser. An animation loop moves one step per flush(). In 'immediate' mode the first step runs right away. The frame that step requests waits for flush() like any other.
  • A frame cancelled by an earlier callback in the same flush() does not run.
  • flushAll() stops after 1000 rounds and throws. Only a loop that never stops requesting frames gets there; step it with flush() instead.
  • A callback that throws stops the flush. The frames after it stay pending, and the next flush() runs them. With onError, the error goes to your function instead (in 'immediate' mode, instead of out of requestAnimationFrame). Rethrow inside it for errors you did not mean to swallow:
ts
import { stubAnimationFrame } from 'vitest-auto-spy/dom-stubs';

const frames = stubAnimationFrame({
  onError: (error) => {
    if (!isExpectedReentrancy(error)) {
      throw error;
    }
  },
});

Common mistake: asserting a cancel against a literal handle such as 1. Handles start above 2^30, so compare with lastHandle:

ts
import { expect } from 'vitest';
import { stubAnimationFrame } from 'vitest-auto-spy/dom-stubs';

const frames = stubAnimationFrame({ mode: 'queued' });

tooltip.show();
tooltip.hide();

expect(frames.cancelAnimationFrame).toHaveBeenLastCalledWith(frames.lastHandle);

Handles start that high so the stub can tell its own from the environment's. A cancel for a handle the stub did not issue goes to the real cancelAnimationFrame. This matters when you install the stub after a render. Zoneless Angular may already have a real frame pending. When Angular cancels it, the real frame is cancelled.

Frames under zoneless Angular ​

Angular 22 runs zoneless by default, in the app and in TestBed. Angular 20 needs provideZonelessChangeDetection() in the testing module.

Zoneless Angular runs change detection from a race: a setTimeout against a requestAnimationFrame, whichever fires first. It starts the race inside the signal write that changed something.

Use 'queued' mode in an Angular spec, and install it before TestBed.createComponent. In 'immediate' mode the race frame runs inside the write, and so does the whole change detection. When that change detection has an effect to run, Angular refuses, and the stub reports it:

text
[vitest-auto-spy] stubAnimationFrame() ran a frame on the spot inside an Angular signal write, and Angular refused to run an effect there: "Schedulers cannot synchronously execute watches while scheduling." …

In 'queued' mode Angular's timer wins the race, and whenStable() waits for it. The component's own frames run when you call flush().

Take a component that measures its host element one frame after render:

ts
import { Component, ElementRef, effect, inject, signal } from '@angular/core';

@Component({ selector: 'app-resize-handle', template: '{{ width() }}px' })
export class ResizeHandleComponent {
  readonly width = signal(0);

  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    effect((onCleanup) => {
      const frame = requestAnimationFrame(() => this.width.set(this.measure()));

      onCleanup(() => cancelAnimationFrame(frame));
    });
  }

  private measure(): number {
    return this.host.nativeElement.getBoundingClientRect().width;
  }
}

The spec queues the frame, gives the host a width of 240, and runs the frame:

ts
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { beforeEach, expect, it } from 'vitest';
import { stubAnimationFrame, stubElementRect } from 'vitest-auto-spy/dom-stubs';

import { ResizeHandleComponent } from './resize-handle.component';

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [provideZonelessChangeDetection()], // Angular 20 only; Angular 22 is zoneless by default
  });
});

it('shows the measured width after the next frame', async () => {
  const frames = stubAnimationFrame({ mode: 'queued' });
  const fixture = TestBed.createComponent(ResizeHandleComponent);

  stubElementRect(fixture.nativeElement, { width: 240 });

  await fixture.whenStable();
  frames.flush(); // the frame the component's effect requested
  await fixture.whenStable();

  expect(fixture.nativeElement.textContent).toContain('240px');
});

A stray frame reported from an Angular spec ​

Stray-timer tracking is what setupAutoSpy({ strayTimers: true }) turns on; trackStrayTimers() starts it by hand. It wraps the real requestAnimationFrame once per worker. A frame requested before the stub is installed, or in a spec that never installs one, goes to the real scheduler. If it is still pending when the file ends, the sweep reports it. Read the first stack line of the report to pick the fix:

The report points atWhat is pendingFix
new YourComponent, a timeout and a frame togetherAngular's own race, in a test that neither waited nor tore TestBed downawait fixture.whenStable() before the test ends, or keep TestBed's default teardown, which cancels the race
The requestAnimationFrame call in your effect or methodThe component's own frame, never cancelledCancel it in onCleanup or DestroyRef.onDestroy. In the spec, also install a 'queued' stub before createComponent. The stub alone only hides the frame from the report
A frame that has to stay on the real scheduler, and that you ownNothing wrongName it in ignore, below

The cancel in the component is the real fix, and it holds outside the test too: see the onCleanup in ResizeHandleComponent above. A 'queued' stub without that cancel also makes the report go away. The stub takes the frame before the tracking sees it, and the frame never runs after the test. So a missing cancel stays hidden, and the leak remains in the app.

ignore matches a substring or a RegExp against the stack of the call that requested the frame, so the component's file name is enough:

ts
import { setupAutoSpy } from 'vitest-auto-spy/setup';

setupAutoSpy({ strayTimers: { ignore: ['resize-handle.component.ts'] } });

Every timer and frame requested from that file is then left alone: not counted, not reported and not cancelled at the end of the file. Prefer a function name, such as 'measureAfterLayout' for effect(function measureAfterLayout() { … }), when the file schedules other timers you still want checked.

stubElementRect(element, rect?) ​

Makes element.getBoundingClientRect() return a box. rect is a DOMRectInit: x, y, width and height, each 0 when left out.

ts
import { stubElementRect } from 'vitest-auto-spy/dom-stubs';

stubElementRect(mapContainer, { width: 800, height: 600 });

mapContainer.getBoundingClientRect(); // DOMRect { x: 0, y: 0, width: 800, height: 600, right: 800, bottom: 600, … }
  • Every call returns a new DOMRect, as the browser does. top, right, bottom and left always match the four numbers.
  • Only this element is patched; other elements still report zeros.
  • It returns an undo function. The undo also carries the installed spy as .getBoundingClientRect, to assert that the measurement happened:
ts
import { expect } from 'vitest';
import { stubElementRect } from 'vitest-auto-spy/dom-stubs';

const stub = stubElementRect(settingsTab, { width: 240 });

component.selectTab('settings');

expect(stub.getBoundingClientRect).toHaveBeenCalled();

vi.resetAllMocks() or mockReset() during a test clears the calls and keeps the box, whichever spy engine you use. The same holds for the stubAnimationFrame spies.

Common mistake on Bun: there, mockReset() drops the box, and the element returns undefined. Call stubElementRect again after a reset.

Taking them off ​

With setupAutoSpy() in your setup file, you do nothing. It runs restoreMockedProps() after every test. That call puts back the previous globals and the element's own method. Without setupAutoSpy(), call restoreMockedProps() from vitest-auto-spy in a global afterEach.

Both stubs install through mockValueProp, the library's property patch that records an undo. restoreMockedProps() replays those undos.

Install them in beforeEach or in the test. A call in beforeAll or a describe body is removed after the first test and is gone for the rest.

stubAnimationFrame also patches document.defaultView when it is a separate object from globalThis, as under happy-dom. view: null patches globalThis only.

Released under the MIT License.