Debug Pemanggil window.scrollTo di Test Jest

1 menit baca.
Tags: JavaScript

Kadang test gagal karena window.scrollTo dipanggil tanpa diduga, tapi stack trace-nya kurang jelas. Ini cara bersih untuk melacak pemanggilnya.

Tambahkan debug spy

Di test setup atau file test yang dituju:

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

Sekarang setiap kali scrollTo dipanggil, Jest mencetak stack trace yang menunjukkan siapa pemicunya.

Pakai spyOn untuk debug sementara

Kalau tidak mau override global:

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();

Scope debug-nya cuma satu test.

Persempit target test

Untuk menemukan component/aksi yang tepat:

  1. jalankan satu file test yang gagal saja
  2. comment out interaksi satu per satu
  3. lihat baris trace yang hilang

Biasanya ini cepat menunjukkan call path-nya.

Pemicu yang umum

  • handler buka/tutup modal
  • effect saat route berubah
  • custom hook yang mengembalikan posisi scroll
  • helper smooth-scroll

Ubah debug jadi assertion

Setelah ketemu pemanggilnya, ganti trace dengan assertion test sungguhan:

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

Ini mencegah regresi nanti.