≪ Today I learned.
RSS購読
    公開日
    タグ
    JavaScript
    著者
    ダーシノ

    Vitest 1.xから2.xにアップデートにするとjest-domのメソッドがエラーになる

    Vitestを1.xから2.xにアップグレードしたところ、testing-library/jest-domが提供するtoBeInTheDocumenttoHaveAttributetoHaveClassなどが見つからないというエラーになった。

    エラー

    Property 'toBeInTheDocument' does not exist on type 'Assertion<HTMLElement>'.
    Property 'toHaveAttribute' does not exist on type 'Assertion<HTMLElement>'.
    Property 'toHaveClass' does not exist on type 'Assertion<HTMLElement>'

    調べてみたところ、Vitestの型定義が変更されたことで発生した問題らしい。

    対処法

    jest-domの型定義を読み込むことで解消できる。

    // vitest.config.mts
    
    // NOTE: jest-domの型を参照ディレクティブで読み込む
    /// <reference types="@testing-library/jest-dom" />
    
    import '@testing-library/jest-dom/vitest'
    import * as matchers from '@testing-library/jest-dom/matchers'
    import { expect } from 'vitest'
    
    expect.extend(matchers)

    fix: proper vitest ts support (#515)のPullRequestがマージされたら、参照ディレクティブも不要になるかも。

    参考