error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install.

I've tried adjusting versions up and down, but haven't had any success.

Interestingly, the $store isn't directly used in any of the components or tests.

Despite trying various fixes from similar problems, like extending types with a shim, nothing seems to be working.

Packages

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99efecfcd9abb7afb7a8ad">[email protected]</a> 
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="741a010c0034465a45415a4c">[email protected]</a>
"@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",

Errors

All failures are showing the same error.

 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)'],
};

Answer №1

It appears that the issue stems from the @vue/composition-api package, specifically with the missing type $store in the interface ComponentInternalInstance.

To resolve this, you can create a file named vuex-shims.d.ts at the root of your project.

import { Store } from 'vuex'


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

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

Answer №2

To start using TypeScript in your project, follow these steps:

  1. Add the TypeScript dependency to your package.json by running: npm install typescript
  2. Create a tsconfig.json file with the following configuration:
{
  "compilerOptions": {
    "esModuleInterop": true,
    "sourceMap": true,
    "module": "esnext",
    "target": "es5",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": ".",
    "experimentalDecorators": true,
    "downlevelIteration": true
  },
  "include": ["**/*.ts", "**/*.vue"],
  "exclude": [
    "node_modules"
  ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Should FormBuilder be utilized in the constructor or is it considered a poor practice?

section, you can find an example of implementation where declarations for formBuilder and services are done within the constructor(). While it is commonly known that using services inside the constructor() is not a recommended practice and should be done ...

Leverage the useRef hook with React Draggable functionality

Having recently delved into coding, I find myself navigating the world of Typescript and React for the first time. My current challenge involves creating a draggable modal in React that adjusts its boundaries upon window resize to ensure it always stays wi ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

Best location to define numerous dialog components

Currently, I have 8 custom Modals that are called in various places within my app. These modals are currently located inside the app.component.html as shown below: <agc class="app-content" [rows]="'auto 1fr'" [height]=" ...

Struggling to locate the ID linked to a specific ObjectId and encountering issues with the import function?

Can someone help me with this issue? Error Message: ERROR TypeError: answerID.equals is not a function I am unsure why I am getting this error. Here is the code snippet: import { ObjectId } from 'bson'; export class Person{ personID: Objec ...

Using TypeScript to ensure class parameter types without affecting properties

I am tasked with defining a schema for "operations" that will be used in my application. This schema must be easily extendable for other groups of "operations" and should include a dictionary of settings for each keyword. Eventually, a "generic caller" wi ...

Issue encountered while creating Next.js 13.4 application: The type 'ResolvingMetadata | undefined' does not meet the requirement of 'ResolvingMetadata'

I'm currently working on dynamically generating metadata for my Next.js 13.4 application using this code snippet: export async function generateMetadata( { params, searchParams }: Props, ) { try { // extract the route parameters ...

One way to transfer data from a Vue table component to another Vue table component is by including an edit button on each row in the table. This allows

When working with two table components, one fetching records using axios and the other needing to get records after clicking on the edit button in the parent component, I encountered issues. Despite attempting Vue's parent-to-child component communica ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

What is the best way to reset an imported file with each test in viTest?

I'm having trouble resetting an imported file completely after each test. I believe that using vi.mock should mimic the original contents of my imported file, but it doesn't seem to be working when I try to modify the file during the tests. Here ...

When redirecting to the same component, Vue.js hooks are not triggered

In my Vuejs project, I have two pages located at the same level with a common component. However, when I redirect from post/new to post/edit/:id, the beforeMount method is not being called. redirect() { this.$router.push({path: `home/post/edit/${this ...

Jest is failing to render data on the screen

I am working on writing unit tests for the following React component: let userData=null; class Login extends React.Component { getData() { $.ajax({ type: "GET", url: myURL, success: function(data) { ...

Looping Angular Components are executed

I am currently developing an Angular application and encountering an issue with my navbar getting looped. The problem arises when I navigate to the /home route, causing the navbar.component.html components to duplicate and appear stacked on top of each oth ...

"Vuex actions fail to return any meaningful value, leading to undefined

Hello everyone, I'm currently working on a login feature using Vue, Vuex, and Axios. However, I'm facing an issue where instead of displaying the user's first name upon logging in, it only shows the access token. Additionally, when I inspect ...

The Nuxt3 application is experiencing technical issues when running in production

My app performs well in development mode when using "npm run dev". However, once I build it with "npm run build" and then launch it with "npm run start", it starts to malfunction. Specifically, the dynamic styles that control whether a button should be d ...

Typescript: defining an interface that inherits properties from a JSON type

When working with TypeScript, I've utilized a generic JSON type as suggested in this source: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} My goal is to cast interface types matching JSON to and ...

Utilizing Apollo and Vue.js to make GraphQL queries with multiple aliases

My Strapi backend is causing me some trouble as I attempt to fetch data from a single collection type into my Vue.js project using Apollo. Everything works smoothly with a single alias, but I'm facing difficulties when trying to work with multiple ali ...

Initiate gapi.auth2 upon VueJs initialization

I am currently developing a Vue.js web application that allows users to connect with their Google accounts. The login process, both front-end and back-end, is functioning properly: the Google sign-in button is displayed, the user clicks on it, and their a ...

Encountering a Nextjs hydration issue after switching languages

I am facing an issue with my Next.js project using version v12.2.4 and implementing internationalization with i18next. The project supports two languages: Italian and English. Strangely, when I switch to English language, the app throws errors, while every ...

Angular 6: Exploring the Challenges of Extending Services Without Sacrificing the Functionality of ChildService

As I was developing multiple angular REST-services for my frontend, I came up with the idea of creating a base class BaseRestService to handle common functionalities like headers and helper functions. However, I encountered TypeErrors when trying to call ...