kulshekhar / ts-jest

A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.
https://kulshekhar.github.io/ts-jest
MIT License
6.97k stars 455 forks source link

when I use vue-router and lazy load components, jest error: Cannot find module '@/views/web/layout.vue' or its corresponding type declarations. #4151

Closed anZong closed 1 year ago

anZong commented 1 year ago

test.spec.js

const routes = [
  {
    component: import('@/views/web/layout.vue'),
  }
]

describe('TestRoutes', () => {
  test('Test1', async () => {
    expect(routes.length).toBe(1)
  })
})
anZong commented 1 year ago

package.json like this:

"dependencies": {
    "@vue/test-utils": "^2.3.2",
    "vite-plugin-compression": "^0.5.1",
    "vue": "^3.2.33",
    "vue-router": "^4.0.15",
    "vuex": "^4.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.21.8",
    "@babel/preset-env": "^7.21.5",
    "@babel/preset-typescript": "^7.21.5",
    "@types/jest": "^29.5.1",
    "@types/node": "^18.11.18",
    "@typescript-eslint/eslint-plugin": "^5.47.1",
    "@typescript-eslint/parser": "^5.47.1",
    "@vitejs/plugin-vue": "^3.2.0",
    "@vue/cli-plugin-babel": "^5.0.8",
    "@vue/cli-plugin-typescript": "^4.5.17",
    "@vue/vue3-jest": "^28.1.0",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^29.5.0",
    "eslint": "^8.30.0",
    "eslint-plugin-vue": "^9.8.0",
    "jest": "^29.5.0",
    "jest-environment-jsdom": "^29.5.0",
    "ts-babel": "^6.1.7",
    "ts-jest": "^29.1.0",
    "typescript": "^4.9.4",
    "vite": "^3.2.3",
    "vite-plugin-eslint": "^1.8.1"
  }
anZong commented 1 year ago

vue-router like this:

 {
        path: '/',
        name: 'Index',
        redirect: '/index',
        component: ()=> import("@/views/web/layout.vue")  
 }
anZong commented 1 year ago

jest.config.json like this:

{
  "preset": "ts-jest",
  "moduleFileExtensions": ["js", "ts", "json", "vue"],
  "extensionsToTreatAsEsm": [".ts", ".vue"],
  "transform": {
    "^.+\\.js$": "babel-jest",
    "^.+\\.vue$": ["@vue/vue3-jest"],
    "^.+\\.ts$": [
      "ts-jest",
      {
        "useESM": true,
        "tsconfig": "<rootDir>/tsconfig.json"
      }
    ]
  },
  "moduleNameMapper": {
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}
anZong commented 1 year ago

Run Jest, get an error:

  ● Test suite failed to run

    src/router/routes.ts:7:32 - error TS2307: Cannot find module '@/views/web/layout.vue' or its corresponding type declarations.

    7         component: ()=> import("@/views/web/layout.vue"),
                                     ~~~~~~~~~~~~~~~~~~~~~~~~

who can help me? Thanks~