Jestでvueコンポーネントのテストを書く際に発生するエラーの対処方法
概要
JestでVueコンポーネントのテストを実行しようとすると、次のようなエラーが発生してしまう
shell$ yarn jest
...
... error TS2307: Cannot find module '~/components/Compoent.vue'
...
環境
依存モジュール
@types/jest
@v26.0.19
ts-jest
@v26.4.4
vue-jest
@v3.0.7
ディレクトリ構成
フロントエンドのソースコードは client
ディレクトリ配下に配置
例) client/pages/index.vue
, client/components/Component.vue
, client/test/components/Component.ts
設定
jest.config.js
及び tsconfig.json
は以下のように設定
jest.config.jsmodule.exports = {
rootDir: "client",
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js',
},
moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
transform: {
'^.+\\.ts$': 'ts-jest',
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue',
]
}
tsconfig.json{
"compilerOptions": {
"target": "ES2018",
"module": "ESNext",
"moduleResolution": "Node",
"lib": [
"ESNext",
"ESNext.AsyncIterable",
"DOM"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"baseUrl": ".",
"paths": {
"~/*": [
"./client/*"
],
"@/*": [
"./client/*"
]
},
"types": [
"@types/node",
"@types/jest",
"@nuxt/types"
]
},
"exclude": [
"node_modules",
".nuxt",
"dist"
]
}
エラー内容
以下のようにテストコードから .vue
ファイルをimportする
typescriptimport Component from "~/components/Component.vue"
test("example", () => {
expect(Component).not.toBeNull()
})
この状態で jest
を実行すると、次のようなエラーが発生してしまう ( error TS2307: Cannot find module '~/components/Compoent.vue'
)
shell$ yarn jest
...
... error TS2307: Cannot find module '~/components/Compoent.vue'
...
解消方法
client/types/vue-shims.d.ts// Adopted from https://github.com/Microsoft/TypeScript-Vue-Starter#single-file-components
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
参考情報