vue typescript jest测试失败-类型上不存在'$store'

xlpyo6sf  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(423)

自从最近的一次npm install以来,我的大多数测试都开始失败。
尝试了各种版本的上升/下降,但没有喜悦。
$store未直接用于任何组件或测试。
我已经尝试了几个修复类似的问题,但似乎没有工作(即扩展类型与shim)。

Package

vue@2.6.14 
nuxt@2.15.8
"@nuxtjs/composition-api": "^0.29.3",
...
"jest-serializer-vue": "^2.0.2",
"@types/jest": "^26.0.8",
"babel-jest": "^26.6.3",
"jest": "^27.5.1",
"ts-jest": "^27.1.4",
"vue-jest": "^3.0.4",

错误

所有失败均具有相同的错误。

FAIL  pages/__tests__/registrationFormP1.spec.ts
 ● Test suite failed to run

node_modules/vuex-composition-helpers/src/util.ts:104:9 - error TS2339: Property '$store' does not exist on type 'ComponentInternalInstance | CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.

104  const {$store} = 'proxy' in vm ? vm.proxy : vm;

...

Test Suites: 7 failed, 9 passed, 16 total
Tests:       61 passed, 61 total

jest.setup.ts

import Vue from 'vue';
import Vuex from 'vuex';
import * as CompositionApi from '@nuxtjs/composition-api/module';
import yapilyStyleguide from '@yapily/styleguide';
Vue.use(yapilyStyleguide);

Vue.use(Vuex);
Vue.use(CompositionApi);

Vue.prototype.$permission = () => jest.fn();

jest.config.ts

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '^vue$': 'vue/dist/vue.common.js',
  },
  moduleFileExtensions: ['ts', 'js', 'vue', 'json', 'jsx', 'json'],
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest',
    '^.+\\.ts?$': 'ts-jest',
  },
  testMatch: ['<rootDir>/**/*.spec.js', '<rootDir>/**/*.spec.ts'],
  collectCoverageFrom: ['<rootDir>/components/**/*.vue', '<rootDir>/pages/**/*.vue', '**/*/*.ts'],
  coveragePathIgnorePatterns: ['/node_modules/', '/types/', '/proto/', '/.nuxt/'],
  setupFilesAfterEnv: ['./jest.setup.ts'],
  snapshotSerializers: ['jest-serializer-vue'],
  transformIgnorePatterns: ['<rootDir>/node_modules/(?!vuex-composition-helpers)'],
};
t8e9dugd

t8e9dugd1#

问题似乎来自@vue/composition-api软件包,接口ComponentInternalInstance没有类型$store
在根项目中创建vuex-shims.d.ts

import { Store } from 'vuex'

declare module '@vue/composition-api' {
  // declare your own store states
  interface State {
    count: number
  }

  // provide typings for `this.$store`
  interface ComponentInternalInstance{
    $store: Store<State> // or Store<any>
  }
}
ldioqlga

ldioqlga2#

1.将typescript相关性添加到您包json:npm安装类型脚本2.创建tsconfig.json文件,其中包含配置:

{
  "compilerOptions": {
    "esModuleInterop" : true,
    "sourceMap": true,
    "module": "esnext",
    "target": "es5",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": ".",
    "experimentalDecorators": true,
    "downlevelIteration": true,
  },
  "include": ["**/*.ts", "**/*.vue"],
  "exclude": [
    "node_modules"
  ]
}

相关问题