4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

<jest> ts error: プロパティ 'toBeInTheDocument' は型 'JestMatchers<HTMLElement>' に存在しません。

Last updated at Posted at 2023-08-26

Next.js v13 のテストに react-testing-library と jest を入れようとした時に遭遇した時のエラー

背景

Next.js の公式に従って jest を setup しました。

terminal
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
# 載ってないけど追加
npm install --save-dev @types/jest

testing-library/jest-dom のインポート用にsetup.jest.js を追加してます。

jest.config.mjs
import nextJest from 'next/jest.js'
 
const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})
 
// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],  // 追加
  testEnvironment: 'jest-environment-jsdom',
}
 
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)
jest.setup.js
import '@testing-library/jest-dom'

エラー

スクリーンショット 2023-08-26 17.48.55.png

解決

tsconfig.json の include に ./jest.setup.js を追加すれば ok

tsconfig.json
{
  "include": [
    // ...
    "./jest.setup.js"
  ],
}

全ては公式に書いてあった

4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?