vue-jest icon indicating copy to clipboard operation
vue-jest copied to clipboard

Cannot import named export from Vue file

Open baffalop opened this issue 2 years ago • 3 comments

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',
}

baffalop avatar Apr 26 '22 13:04 baffalop

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.

lmiller1990 avatar May 17 '22 02:05 lmiller1990

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")

scbj avatar Feb 21 '23 12:02 scbj

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?

lmiller1990 avatar Feb 27 '23 01:02 lmiller1990