vuejs / vue-jest

Jest Vue transformer
MIT License
744 stars 157 forks source link

Cannot import named export from Vue file #466

Open baffalop opened 2 years ago

baffalop commented 2 years ago

I'm using vue-jest 4.0.1 with @jest/core 26.6.3 (via vue-cli-service test).

I can't seem to import named exports from a Vue SFC. For example, in my vue file I have:

<script lang="ts">
import Vue from 'vue'

export interface MyProp {
  // ...
}

export default Vue.extend({
  // ...
})
</script>

And in my test, I have:

import MyComponent, { MyProp } from '@components/MyComponent.vue'

When running the test I get a typescript error:

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
MyComponent.ts:2:26 - error TS2614: Module '"*.vue"' has no exported member 'MyProp'. Did you mean to use 'import MyProp from "*.vue"' instead?

The same happens for named exports that are values, not types.

Config

The relevant parts of jest.config.js are:

module.exports = {
  moduleFileExtensions: [
    'js',
    'json',
    'vue',
    'jsx',
    'ts',
    'tsx',
  ],

  transform: {
    '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
    '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
  },

  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
}
lmiller1990 commented 2 years ago

It looks like the generic *.vue shim is the problem - I'm fairly sure we have tests for the actual feature you are describing.

Can you try configuring isolatedModules? https://huafu.github.io/ts-jest/user/config/isolatedModules to ignore this error?

You will lose some type safety, but it should work. This is what I do. I then run vue-tsc in another process/as part of my CI pipeline, or rely on Volar, to get the actual type checks.

scbj commented 1 year ago

I have the same problem, it is not possible to use named import from a .vue file in a unit test file. Indeed the generic shim ^.+\\.vue$ doesn't allow named import.. If anyone has a solution I'm listening (except "move the export to another file")

lmiller1990 commented 1 year ago

Are you even allowed to have a named export in script setup? According to the docs, this isn't supported: https://vuejs.org/api/sfc-script-setup.html#usage-alongside-normal-script (I could be wrong, I haven't tried this - I just assumed it wasn't meant to work).

I know it "kind of" works with vue-tsc and Volar (eg, types), but is it actually valid code when exporting an actual JS object?