2

Jest Configuration:

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest',
  moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'vue'],
  moduleNameMapper: {
    '^~/(.*)$': '<rootDir>/src/$1',
  },
  testEnvironment: 'jsdom',
  testMatch: ['**/tests/unit/**/*.[jt]s?(x)'],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '^.+\\.ts$': 'ts-jest',
  },
}

My test file (.ts file) :

import { render } from '@testing-library/vue'
import Kaki from '~/components/Kaki.vue'

test('Kaki.vue', () => {
  const { getByText } = render(Kaki)
  getByText('Tono')
})

Here's my directory structure:

Directory Structure

When I run the test, it says Cannot find module '~/components/Kaki.vue' or its corresponding type declarations.

I think it has something to do with moduleNameMapper

Erick Christian
  • 98
  • 2
  • 11

1 Answers1

3

Can you check if it works if you change your Index.spec.ts to a .js file? The error you're getting is because TypeScript doesn't know what type should .vue files have.

In a new Vue CLI project, the error you're getting is prevented with the shims.d.ts which tells TS to treat *.vue files as if their default export had the Vue type.

The "correct" solution here is to figure out why isn't shims.d.ts telling TypeScript the type for *.vue files (which is why you're getting the "Cannot find module [...] or its corresponding type declarations" error

Another thing is - this is not a real solution but a temporary fix:

// @ts-ignore
import Kaki from '~/components/Kaki.vue'

Another thing you could try is importing Kaki with a relative path (so without the ~ alias)? The ~ alias may be broken in some way - are you sure the alias is correctly defined in your tsconfig.json?

  • I did try to use relative but it's still broken, so the solution was actually the `shims.d.ts`. I tried to recreate [this template](https://github.com/DiegoFT/vue3-vite-template/blob/main/src/types/shims-vue.d.ts) but forgot the declaration file. Thanks man – Erick Christian Aug 30 '21 at 02:40
  • Hi, I've tried @ts-ignore and it worked, thank you. But I have also shims.d.ts file. Still don't understand why ts-ignore needed. Do you have any idea? I've also explained my problem here [link](https://stackoverflow.com/questions/70983053/vue3-jest-module-not-found-error-while-using-store) – Oğuz Öztınaz Feb 04 '22 at 11:30