Debugging 'window.scrollTo' Invocation for Identifying the Caller

5 min read.
Tags: javascript

Sometimes tests fail because window.scrollTo is called unexpectedly, but the stack trace is not clear enough. Here is a clean way to track the caller.

Add a debug spy

In your test setup or target test file:

window.scrollTo = jest.fn(() => {
  // eslint-disable-next-line no-console
  console.trace('scrollTo called');
});

Now whenever scrollTo is called, Jest prints a stack trace showing who triggered it.

Use spyOn for temporary debug

If you prefer no global override:

const spy = jest.spyOn(window, 'scrollTo').mockImplementation(() => {
  // eslint-disable-next-line no-console
  console.trace('scrollTo called from test');
});

// run test scenario here

spy.mockRestore();

This keeps the debug scope limited to one test.

Narrow the test target

To find the exact component/action:

  1. run only one failing test file
  2. comment out interactions step by step
  3. check the trace line that disappears

That usually shows the exact call path quickly.

Common trigger points

  • modal open/close handlers
  • route change effects
  • custom hooks that restore scroll position
  • smooth-scroll helper utilities

Convert debug into assertion

After finding the caller, replace trace with real test assertion:

expect(window.scrollTo).toHaveBeenCalledWith({ top: 0, behavior: 'smooth' });

This avoids future regressions.

Related Posts
Latest Posts