2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vitest】TypeError: candidate?.scrollIntoView is not a function

2
Posted at

はじめに

こんにちは!POMです。
React × TypeScriptのWebアプリを個人開発中なのですが、
その際にVitestでのテスト実装中に出たエラーと解決方法について記事に残します。

問題

Vitestでテストを実行した際に下記エラーが出ました。

TypeError: candidate?.scrollIntoView is not a function

環境(一部抜粋)

vitest: "^4.1.3"
@testing-library/dom": "^10.4.1"
@testing-library/jest-dom": "^6.9.1"
@testing-library/react": "^16.3.2"
jsdom: "^29.0.2"
shadcn: "^4.1.2"

解決方法

JSDOM環境では、scrollIntoViewメソッドが実装されていないため、vitest-setup.ts(使用しているセットアップファイル)内で、Element.prototype.scrollIntoViewをモックすることで解決しました。

vitest-setup.ts
import '@testing-library/jest-dom';

// Pointer Events API が JSDOM に無いため、ダミー実装を追加
const noop = () => {};

// 戻り値が必要な関数は false を返す
if (!HTMLElement.prototype.hasPointerCapture) {
    HTMLElement.prototype.hasPointerCapture = () => false;
}

// 副作用系は noop でOK
if (!HTMLElement.prototype.setPointerCapture) {
    HTMLElement.prototype.setPointerCapture = noop;
}

if (!HTMLElement.prototype.releasePointerCapture) {
    HTMLElement.prototype.releasePointerCapture = noop;
}

+ window.HTMLElement.prototype.scrollIntoView = function() {};

なお、vitest-setup.ts内の他記述については
当該アプリでshadcn/uiを導入していることで、
別に発生したエラーを解決するために、
下記記事を参考に追記したものになります。

おわりに

vitestでのテスト実装は以前から何度か経験していますが、
前も似たようなエラー見たな〜ということが
少しずつ増えてきました。
エラーと向き合うことで自分の知見を増やしていきたいです。

参考記事

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてくださ!
▼▼▼

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?